Joining Arrays in Python: Merging and Concatenation Methods
Discover how to join or merge two arrays in Python using methods like append()
and extend()
. Learn the best practices for concatenating arrays and ensuring data type compatibility to avoid errors.
Python - Join Arrays
Joining two arrays is also known as merging or concatenating. Python provides multiple ways to merge two arrays, such as using append()
and extend()
methods. Before merging, ensure that both arrays are of the same data type to avoid errors.
In Python, an array is a homogeneous collection of built-in data types like strings, integers, or floats. The array itself is not a built-in type, so we use Python's built-in array module.
Merge Python Array
Join two Arrays in Python
To join arrays in Python, you can use the following approaches:
- Using
append()
method - Using
+
operator - Using
extend()
method
Using append()
Method
To join two arrays, append each item from one array to another using the append()
method. Run a for loop on the original array, fetch each element, and append it to a new array.
Example: Join Two Arrays by Appending Elements
import array as arr
# creating two arrays
a = arr.array('i', [10, 5, 15, 4, 6, 20, 9])
b = arr.array('i', [2, 7, 8, 11, 3, 10])
# merging both arrays
for i in range(len(b)):
a.append(b[i])
print(a)
Output
array('i', [10, 5, 15, 4, 6, 20, 9, 2, 7, 8, 11, 3, 10])
Using +
Operator
We can also use the +
operator to concatenate or merge two arrays. First, convert arrays to list objects, concatenate the lists using the +
operator, and convert back to get the merged array.
Example: Join Two Arrays by Converting to List Objects
import array as arr
a = arr.array('i', [10, 5, 15, 4, 6, 20, 9])
b = arr.array('i', [2, 7, 8, 11, 3, 10])
x = a.tolist()
y = b.tolist()
z = x + y
a = arr.array('i', z)
print(a)
Output
array('i', [10, 5, 15, 4, 6, 20, 9, 2, 7, 8, 11, 3, 10])
Using extend()
Method
Another approach to concatenate arrays is the use of the extend()
method from the List class. First, convert the array to a list, then call the extend()
method to merge the two lists.
Example: Join Two Arrays using extend()
Method
import array as arr
a = arr.array('i', [88, 99, 77, 66, 44, 22])
b = arr.array('i', [12, 17, 18, 11, 13, 10])
a.extend(b)
print(a)
Output
array('i', [88, 99, 77, 66, 44, 22, 12, 17, 18, 11, 13, 10])