Python Program to Merge Two Arrays
You can merge two arrays in Python by using the
+ operator like merged = array1 + array2 or by using array1.extend(array2) to add elements of the second array to the first.Examples
Input[1, 2, 3], [4, 5, 6]
Output[1, 2, 3, 4, 5, 6]
Input[], [7, 8]
Output[7, 8]
Input[10], []
Output[10]
How to Think About It
To merge two arrays, think of putting all elements from the second array right after the first array's elements. You can do this by creating a new array that contains all elements from both arrays or by adding the second array's elements directly to the first one.
Algorithm
1
Get the first array.2
Get the second array.3
Combine the two arrays by adding the second array's elements to the first.4
Return or print the merged array.Code
python
array1 = [1, 2, 3] array2 = [4, 5, 6] merged = array1 + array2 print(merged)
Output
[1, 2, 3, 4, 5, 6]
Dry Run
Let's trace merging [1, 2, 3] and [4, 5, 6] using the + operator.
1
Start with two arrays
array1 = [1, 2, 3], array2 = [4, 5, 6]
2
Add arrays using +
merged = array1 + array2 results in [1, 2, 3, 4, 5, 6]
3
Print merged array
Output: [1, 2, 3, 4, 5, 6]
| Operation |
|---|
| merged = [1, 2, 3] + [4, 5, 6] |
| merged = [1, 2, 3, 4, 5, 6] |
Why This Works
Step 1: Using + operator
The + operator creates a new array by joining elements of both arrays in order.
Step 2: Using extend() method
The extend() method adds elements of the second array to the end of the first array, modifying it in place.
Alternative Approaches
Using extend() method
python
array1 = [1, 2, 3] array2 = [4, 5, 6] array1.extend(array2) print(array1)
This modifies the first array directly instead of creating a new one.
Using unpacking operator
python
array1 = [1, 2, 3] array2 = [4, 5, 6] merged = [*array1, *array2] print(merged)
This creates a new array by unpacking elements from both arrays, useful for readability.
Complexity: O(n + m) time, O(n + m) space
Time Complexity
Merging requires visiting each element of both arrays once, so time grows with the total number of elements.
Space Complexity
Using + or unpacking creates a new array needing space for all elements; extend() modifies in place, saving space.
Which Approach is Fastest?
extend() is faster and uses less memory since it modifies the first array without creating a new one.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using + operator | O(n + m) | O(n + m) | When you want a new merged array |
| Using extend() | O(m) | O(1) | When you want to add to the first array directly |
| Using unpacking | O(n + m) | O(n + m) | Readable new array creation |
Use
+ for a new merged array or extend() to add elements to the first array directly.Trying to use
append() to merge arrays, which adds the entire second array as one element instead of merging.