How to merge two lists in Python
Discover multiple ways to merge two lists in Python. This guide covers methods, tips, applications, and how to debug common errors.

The ability to merge lists is a common need in Python, essential for data manipulation and algorithm design. Python provides several methods, from the simple + operator to versatile functions.
In this article, we'll explore several techniques to combine lists. We'll cover practical tips, real-world applications, and debugging advice that will help you master each method and choose the right one.
Using the + operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)--OUTPUT--[1, 2, 3, 4, 5, 6]
The + operator offers the most direct way to concatenate two lists. It works by creating a new list that contains all the elements from the first list, followed by all the elements from the second.
Crucially, this operation is non-destructive. Your original lists, list1 and list2, remain completely unchanged. This makes the + operator a safe and predictable choice for simple merge operations where preserving the original data is a priority.
Basic list merging techniques
While the + operator is great for simple concatenation, Python also provides more specialized tools like the extend() method, itertools.chain(), and list comprehensions.
Using the extend() method
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)--OUTPUT--[1, 2, 3, 4, 5, 6]
Unlike the + operator, the extend() method modifies a list in place. It takes an iterable, such as list2, and appends each of its elements to the end of list1. This approach is often more memory-efficient for large lists because it doesn't create a new list object, similar to other methods for adding to a list in Python.
- The key difference is that
extend()is a destructive operation—it permanently alters the original list. - The method returns
None, so you can't use it for assignment likenew_list = list1.extend(list2).
Using itertools.chain()
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list(itertools.chain(list1, list2))
print(merged_list)--OUTPUT--[1, 2, 3, 4, 5, 6]
The itertools.chain() function offers a memory-efficient way to merge lists. It creates an iterator that seamlessly pulls elements from each list in sequence, one after another. This approach is ideal for very large lists, as it avoids allocating memory for a brand new list all at once.
- It returns a special iterator, so you must wrap the result in
list()to create an actual list object. - Like the
+operator,itertools.chain()is non-destructive and leaves your original lists unchanged.
Using list comprehension
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [item for sublist in [list1, list2] for item in sublist]
print(merged_list)--OUTPUT--[1, 2, 3, 4, 5, 6]
List comprehension provides a concise and powerful syntax for creating new lists. This one-liner uses a nested loop: the outer loop, for sublist in [list1, list2], iterates through your main lists, and the inner loop, for item in sublist, unpacks the elements from each. This technique is also useful when creating a list of lists in Python.
- It’s a non-destructive operation that creates an entirely new list, leaving the original lists untouched.
- This method is highly flexible, as you can easily add conditional logic to filter or transform elements during the merge.
- While elegant, its readability can decrease with more complex operations compared to simpler methods.
Advanced list merging techniques
Building on those foundational methods, you can tackle more complex merging tasks using the unpacking operator *, removing duplicates, or leveraging high-performance libraries.
Using the unpacking operator *
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [*list1, *list2]
print(merged_list)--OUTPUT--[1, 2, 3, 4, 5, 6]
The unpacking operator * provides a highly readable and modern way to merge lists. It works by taking the elements out of an iterable and placing them into a new list literal. In the expression [*list1, *list2], Python effectively expands it to [1, 2, 3, 4, 5, 6] before creating the final list.
- This operation is non-destructive and always creates a new list, leaving the original lists untouched.
- Its main advantage is clarity, making your intent immediately obvious to anyone reading the code.
Merging lists while removing duplicates
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
merged_list = list(dict.fromkeys(list1 + list2))
print(merged_list)--OUTPUT--[1, 2, 3, 4, 5, 6]
You can efficiently merge lists and remove duplicates by leveraging a dictionary's properties. This method first combines your lists with the + operator. The resulting list is then passed to dict.fromkeys(). This is just one approach to removing duplicates from a list in Python.
- This function creates a dictionary using the list items as keys. Since dictionary keys must be unique, duplicates are automatically discarded.
- Finally, wrapping the result in
list()converts these unique keys back into a new list, preserving the order of each element's first appearance.
Using NumPy for high-performance merging
import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
merged_array = np.concatenate((array1, array2))
merged_list = merged_array.tolist()
print(merged_list)--OUTPUT--[1, 2, 3, 4, 5, 6]
For large-scale numerical data, NumPy provides a high-performance solution. The library is optimized for speed, making it a go-to for data science and scientific computing where performance is critical.
- First, you convert your Python lists into NumPy arrays using
np.array(). - Then, the
np.concatenate()function merges these arrays with exceptional efficiency. - The operation returns a new NumPy array, which you can easily convert back to a standard list with the
.tolist()method.
Move faster with Replit
Replit is an AI-powered development platform that lets you skip setup and start coding Python instantly. It comes with all dependencies pre-installed, so you don't have to worry about environment configuration.
Mastering individual techniques is one thing, but building a complete application is another. Instead of just piecing methods together, you can use Agent 4 to build a full app from a simple description. It handles everything from writing the code to connecting databases and deploying your project.
For example, instead of manually merging lists, you could ask Agent 4 to build:
- A data cleaning tool that merges several lists of raw data and removes duplicates to create a single, clean dataset.
- An inventory tracker that combines lists of incoming and outgoing stock to maintain a real-time count.
- A log analyzer that concatenates event logs from multiple sources into one sequential timeline for easier debugging.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with simple operations like merging lists, a few common pitfalls can trip you up if you're not careful.
Fixing confusion between append() and extend()
A frequent mix-up is confusing the append() and extend() methods. They sound similar, but their behavior is quite different. The append() method adds its entire argument as a single new element to the end of a list. If you append a list, you get a nested list. In contrast, extend() takes an iterable, like another list, and adds each of its elements individually, which is what you want for a flat merge. For more details on using append in Python, see our comprehensive guide.
Avoiding unintended list modifications with .extend()
Because extend() modifies a list in place, it can lead to unexpected side effects. It's a destructive operation, meaning the original list is permanently changed. Another common mistake is trying to assign the result of extend() to a new variable. The method returns None, so you'll end up with an empty variable and a modified original list—a confusing bug to track down.
Handling type errors when merging with +
The + operator is straightforward, but it has one strict rule: you can only use it to concatenate a list with another list. Attempting to add a list to a different data type, like an integer or a string, will result in a TypeError. Python doesn't know how to combine these different types, so it stops execution with an error.
Fixing confusion between append() and extend()
It’s easy to confuse append() with extend(), but they behave very differently. Using append() to merge two lists doesn't combine their elements. Instead, it nests the second list inside the first one. The following code demonstrates this common mistake.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.append(list2)
print(list1)
The output is [1, 2, 3, [4, 5, 6]]. The append() method adds list2 as a single nested element instead of merging its items. See the correct approach below for achieving a flat merge.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
The correct approach uses the extend() method because it unpacks the second list and adds each of its elements to the first. This creates the intended flat merge, rather than a nested list. Always remember that extend() is a destructive operation—it modifies list1 in place. This is the crucial detail to keep in mind, especially when you need to keep your original lists intact for other parts of your program.
Avoiding unintended list modifications with .extend()
The extend() method is a destructive operation, meaning it permanently alters the list it's called on. This can cause unexpected bugs if you need to preserve your original data for other tasks. The code below demonstrates this exact problem in action.
original = [1, 2, 3]
additional = [4, 5, 6]
original.extend(additional)
print(original)
print("Original data preserved:", original == [1, 2, 3])
Because extend() alters the list directly, the final comparison original == [1, 2, 3] returns False, proving the original data was overwritten. Check the code below for a way to avoid this while still merging the lists.
original = [1, 2, 3]
additional = [4, 5, 6]
merged = original + additional
print(merged)
print("Original data preserved:", original == [1, 2, 3])
To avoid modifying your original data, use the + operator instead of extend(). This approach creates an entirely new list, leaving the source lists untouched. The final check, original == [1, 2, 3], returns True, proving the original data is preserved. This non-destructive method is the safest choice whenever you need to keep your initial lists intact for other operations, preventing hard-to-find bugs down the line. When preservation is critical, consider other techniques for copying a list in Python.
Handling type errors when merging with +
The + operator is strict: it only concatenates a list with another list. If you try to add a different data type, such as a string from user input, Python will stop and raise a TypeError. See what happens below.
numbers = [1, 2, 3]
user_input = "4" # Simulating user input as string
result = numbers + user_input
print(result)
This operation fails because the + operator can't combine a list with a string like "4". Python requires both items to be lists for concatenation. The code below shows how to properly prepare and merge the data.
numbers = [1, 2, 3]
user_input = "4" # Simulating user input as string
result = numbers + [int(user_input)]
print(result)
To fix the TypeError, you must ensure both operands are lists. The solution first converts the user_input string to a number using int(). Then, it places that number inside a new list: [int(user_input)]. Now, the + operator can correctly concatenate the two lists. This error often appears when processing data from external sources like user input or files, which frequently arrive as strings and require explicit type conversion before list operations.
Real-world applications
Now that you've navigated the common pitfalls, you can see how these merging techniques are used to solve practical, everyday programming problems.
Combining movie watchlists with the + operator
The + operator is ideal for straightforward tasks like merging two separate movie watchlists into a single, unified list for family movie night.
parent_watchlist = ["Inception", "The Matrix", "Interstellar"]
child_watchlist = ["Frozen", "Toy Story", "The Lion King"]
family_watchlist = parent_watchlist + child_watchlist
print("Family movie night options:")
for movie in family_watchlist:
print(f"- {movie}")
This code uses the + operator to create a new list, family_watchlist, by joining two existing ones. The resulting list contains all items from parent_watchlist followed by every item from child_watchlist.
- A key takeaway is that this operation is non-destructive. Both original lists remain completely unchanged.
Finally, the for loop iterates through the newly created list, using an f-string to format and print each movie title. It’s a clean way to aggregate data before displaying it.
Analyzing sales data after merging with the + operator
The + operator is also great for consolidating numerical data, like sales figures from different stores, so you can analyze the combined dataset with functions like sum(), max(), and min().
store1_sales = [1200, 1500, 900]
store2_sales = [1000, 1300, 1100]
all_sales = store1_sales + store2_sales
average_sale = sum(all_sales) / len(all_sales)
highest_sale = max(all_sales)
lowest_sale = min(all_sales)
print(f"Average sale: ${average_sale:.2f}")
print(f"Highest sale: ${highest_sale}")
print(f"Lowest sale: ${lowest_sale}")
This code first merges two sales lists, store1_sales and store2_sales, into a single list called all_sales using the + operator. Once the data is consolidated, you can easily perform aggregate analysis on the complete dataset.
- The average sale is calculated by dividing the total from
sum(all_sales)by the item count fromlen(all_sales). - The built-in
max()andmin()functions are then used to quickly find the highest and lowest sales figures across both stores.
This approach shows how merging is often the first step before analyzing or summarizing data from multiple sources.
Get started with Replit
Turn your knowledge into a real tool. Tell Replit Agent to “build a tool that merges sales data from two stores” or “create a script that combines two user lists and removes duplicates.”
Replit Agent will write the code, test for errors, and deploy your app. You just provide the prompt. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



