How to merge two arrays in Python
Learn how to merge two arrays in Python. Explore different methods, tips, real-world applications, and common error debugging.

You often need to merge arrays in Python for data manipulation and algorithm design. Python provides several efficient methods, from simple operators to built-in functions, to accomplish this task.
In this article, you'll explore several techniques to combine arrays. You'll find everything from the + operator to advanced functions, with practical tips, real-world applications, and essential debugging advice.
Using the + operator to join lists
array1 = [1, 2, 3]
array2 = [4, 5, 6]
merged_array = array1 + array2
print(merged_array)--OUTPUT--[1, 2, 3, 4, 5, 6]
The + operator provides the most direct way to concatenate lists. In Python, this operator is overloaded for list objects, meaning it joins them end-to-end rather than performing a mathematical sum. The operation creates a new list in memory, which is an important distinction from methods that modify a list in-place. This behavior is similar to other techniques for copying lists in Python.
This approach is highly valued for a few key reasons:
- Readability: The code is clean and its intent is immediately clear.
- Safety: It’s a non-destructive operation. The original lists,
array1andarray2, remain completely unchanged.
Basic merging techniques
Beyond the straightforward + operator, Python offers several other fundamental methods for merging lists, each with its own unique advantages and use cases.
Using the extend() method to combine lists
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array1.extend(array2)
print(array1)--OUTPUT--[1, 2, 3, 4, 5, 6]
Unlike the + operator, the extend() method modifies a list in-place. It appends all elements from an iterable, like array2, directly to the end of the first list, array1. This follows the same principles as other methods for adding elements to lists.
- In-place modification: The original list,
array1, is permanently altered. The method doesn't return a new list. - Memory efficiency: Because it modifies the existing list,
extend()is often more efficient than concatenation, especially when working with large datasets.
Using the * unpacking operator
array1 = ['a', 'b', 'c']
array2 = ['d', 'e', 'f']
merged_array = [*array1, *array2]
print(merged_array)--OUTPUT--['a', 'b', 'c', 'd', 'e', 'f']
The * operator, introduced in Python 3.5, offers a highly flexible way to merge lists. It "unpacks" the elements from each list. In the expression [*array1, *array2], Python takes all items from array1 and array2 and places them sequentially into a new list.
- Flexibility: It's incredibly versatile. You can easily insert other elements or even other unpacked iterables anywhere in the new list, like
[0, *array1, *array2, 100]. - Readability: The syntax is modern and often considered more expressive than simple concatenation, especially for complex merges.
Merging with list comprehension
array1 = [10, 20, 30]
array2 = [40, 50, 60]
merged_array = [item for array in (array1, array2) for item in array]
print(merged_array)--OUTPUT--[10, 20, 30, 40, 50, 60]
List comprehension provides a compact and powerful way to merge lists. The expression [item for array in (array1, array2) for item in array] works by nesting loops. The outer loop iterates through a tuple of your lists, and the inner loop unpacks each item into the new, merged list. This demonstrates advanced techniques for iterating through lists.
- Flexibility: This method is highly adaptable. You can easily add conditional logic to filter elements or transform them during the merge process.
- Conciseness: It's a classic "Pythonic" one-liner that combines loop logic and list creation into a single, readable statement.
Advanced array operations
If the basic methods don't quite cut it for performance or complexity, you can turn to specialized libraries and advanced techniques for more demanding merges.
Using NumPy to merge arrays
import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
merged_array = np.concatenate((array1, array2))
print(merged_array)--OUTPUT--[1 2 3 4 5 6]
NumPy is a powerful library for numerical computing, offering high-performance array objects. When you need to merge large datasets efficiently, the np.concatenate() function is your best bet. It joins a sequence of arrays along a specified axis, creating a new array in the process.
- Performance: NumPy operations are written in C and are significantly faster than standard Python loops, especially for numerical tasks.
- Syntax: The function takes a tuple of arrays to be joined, such as
(array1, array2), and returns a new, merged array.
Using itertools.chain() for efficient merging
from itertools import chain
array1 = [1.5, 2.5, 3.5]
array2 = [4.5, 5.5, 6.5]
merged_array = list(chain(array1, array2))
print(merged_array)--OUTPUT--[1.5, 2.5, 3.5, 4.5, 5.5, 6.5]
The itertools.chain() function offers a highly memory-efficient way to merge lists. Instead of creating a new list, it returns an iterator that treats the input lists as a single, continuous sequence. This approach is especially useful when working with very large datasets because it avoids allocating memory for a new list all at once.
- Memory-efficient: It processes elements on the fly without building an intermediate list, making it great for performance.
- Lazy evaluation: The actual merging only happens as you iterate. You need to use
list()to force the creation of a new list from the iterator.
Merging arrays with custom interleaving
array1 = ['a', 'b', 'c']
array2 = [1, 2, 3]
merged_array = [item for pair in zip(array1, array2) for item in pair]
print(merged_array)--OUTPUT--['a', 1, 'b', 2, 'c', 3]
For more complex patterns, you can interleave elements from multiple lists. This technique combines the zip() function with a nested list comprehension to create a new list with alternating items from the originals.
- The
zip()function pairs corresponding elements from each list, creating tuples like('a', 1). - A list comprehension then iterates through these pairs, unpacking each one to build the final interleaved list.
It's a powerful way to weave two sequences together. Note that zip() stops as soon as the shortest list runs out of items. This technique works well alongside other list manipulation methods like slicing lists in Python.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. It helps you move from learning individual techniques to building complete applications with Agent 4, which handles everything from code and databases to APIs and deployment based on your description.
Instead of just piecing together lists, you can describe the app you want to build. Agent 4 can create practical tools that use these functions, such as:
- A playlist merger that combines tracks from several lists into a single, unified playlist.
- A log processor that interleaves timestamps and event messages from two separate arrays to create a chronological report.
- A data exporter that merges multiple datasets and filters out duplicates before generating a final output.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Merging arrays is usually straightforward, but you can run into a few common pitfalls if you're not careful.
- Fixing type errors when using the
+operator: The+operator is strict about types. You can't add a list to a non-list type, like an integer, without causing aTypeError. Always make sure both operands are lists before you try to concatenate them. - Understanding in-place modification with
extend(): A frequent mistake is assigning the result oflist.extend()to a variable. Because theextend()method modifies the original list directly and returnsNone, your variable will be empty. If you need a new list, stick with the+operator or the unpacking*operator. - Attempting to merge dictionaries with the
+operator: The+operator is defined for sequences like lists, not for mappings like dictionaries. Trying to combine two dictionaries with+will only raise aTypeError. For dictionaries, you'll want to use theupdate()method or the merge|operator instead.
Fixing type errors when using the + operator
The + operator is strictly for concatenating two lists. If you try to add a non-list item—like an integer—you'll get a TypeError because the operation is undefined for mismatched types. This is a common mistake. The code below demonstrates this error in action.
numbers = [1, 2, 3]
new_number = 4
combined = numbers + new_number
print(combined)
This operation fails because new_number is an integer, not a list, and the + operator can't combine these different types. The corrected code below demonstrates how to properly add the new number to the list.
numbers = [1, 2, 3]
new_number = 4
combined = numbers + [new_number]
print(combined)
The fix is to wrap new_number in square brackets, turning it into a single-item list: [new_number]. Now that both operands are lists, the + operator can concatenate them into a new list as intended. You'll run into this scenario when you need to add an element and create a new list, rather than using a method like append() which modifies the original list without returning a new one.
Understanding in-place modification with extend()
It's easy to forget that the extend() method works in-place, modifying the original list directly. A common pitfall is assigning its return value to a variable, but since extend() returns None, the result isn't what you expect. See what happens below.
original = [1, 2, 3]
extension = [4, 5]
result = original.extend(extension)
print(result)
print(original)
The result variable is assigned the output of original.extend(extension), which is None. While original is updated correctly, result is left empty. The corrected code below shows how to get the intended outcome.
original = [1, 2, 3]
extension = [4, 5]
original.extend(extension)
result = original
print(result)
The correct approach is a two-step process. First, call original.extend(extension) to modify the original list directly. Since the change happens in-place, you then assign the modified original list to your result variable. This ensures result contains the merged list instead of None. It's a crucial pattern when you need to continue working with the merged list under a new name or pass it to another function.
Attempting to merge dictionaries with the + operator
The + operator is designed for sequences like lists, not for mappings like dictionaries. It's a common mistake to assume it works for both. Trying to concatenate two dictionaries with + will result in a TypeError. See what happens below.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = dict1 + dict2
print(merged_dict)
This code fails because the + operator isn't defined for dictionaries. It's designed for sequences, not key-value pairs, which causes a TypeError. The corrected code below shows the right way to merge them.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
To merge dictionaries, use the double-asterisk ** unpacking operator. This operator unpacks the key-value pairs from each dictionary into a new one. The expression {**dict1, **dict2} creates a new dictionary containing all items from both originals. It's the modern, Pythonic way to combine dictionaries. You'll find this useful when merging configuration settings or combining data from different sources into a single structure.
Real-world applications
With the methods and error handling covered, you can apply these techniques to solve practical, real-world data challenges.
Combining user data from multiple sources with +
Imagine you have two lists of customer IDs—one from your website's registration and another from a recent marketing campaign. To send a newsletter to everyone, you need to combine these lists into a single master list.
The + operator is a perfect fit for this task. It lets you concatenate the two lists into a new one without altering the originals. This is a huge advantage because it preserves the integrity of your source data, making it easy to track where each group of users came from.
Creating a unique movie recommendation list with set()
Let's say you and a friend both have lists of favorite movies, and you want to create a combined watchlist. If you simply merge the lists, you'll likely end up with duplicates for any movies you both enjoy.
This is where Python's set() comes in handy. A set is a data structure that, by its nature, only holds unique items. When you convert a list to a set, all duplicate entries are automatically discarded. This is one of several effective techniques for removing duplicates from lists.
You can merge your two movie lists using the + operator and then convert the resulting list into a set to instantly create a unique collection. If you need the final output to be a list, you can easily convert it back. This technique is a go-to for data cleaning tasks where removing duplicates is essential.
Combining user data from multiple sources with +
When you're working with structured data, like user profiles and activity logs, the + operator offers a simple way to combine lists of dictionaries into a single dataset.
user_profiles = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
user_activities = [{'id': 1, 'logins': 27}, {'id': 2, 'logins': 14}]
combined_data = user_profiles + user_activities
print(combined_data)
This code uses the + operator to concatenate the user_profiles and user_activities lists. It creates a new list, combined_data, that holds all the dictionary elements from both lists, appended in sequence.
- The operation is non-destructive, so your original lists remain unchanged.
- It performs a simple list concatenation, not a "smart" merge of the dictionaries. Dictionaries with the same
idare not combined into one.
This method is ideal when you need a simple, flat collection of records from different sources before performing more complex processing.
Creating a unique movie recommendation list with set()
When you merge movie recommendations from two different lists, you can use set() to automatically remove any overlapping titles and create a single watchlist.
netflix_recommendations = [301, 302, 304, 308]
hulu_recommendations = [302, 305, 307, 308]
all_recommendations = netflix_recommendations + hulu_recommendations
unique_recommendations = list(set(all_recommendations))
print(f"All recommendations: {all_recommendations}")
print(f"Unique recommendations: {unique_recommendations}")
This code demonstrates a practical way to merge and deduplicate data. The first step joins the two lists with the + operator. This creates all_recommendations, which contains every item from both original lists, including duplicates like 302 and 308.
- The
list(set(all_recommendations))expression then creates a new list calledunique_recommendations. - This is a common and efficient technique for filtering out any repeated movie IDs from a collection.
The final output contrasts the simple merged list with the clean, unique version, a frequent task in data processing.
Get started with Replit
Now, turn these techniques into a real tool. Tell Replit Agent what to build, like: "Create a playlist merger for two song lists" or "Build a script that interleaves two log files by timestamp."
It writes the code, tests for errors, and deploys the app for you. 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.



