How to Combine Arrays in Python
To combine arrays in Python, you can use the + operator, the extend() function, the append() function, or the itertools.chain() function.
The following examples show how to combine arrays in Python.
Using + Operator
We can use the + operator to combine arrays.
Suppose we have the following arrays:
# Create arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]
# Combine arrays
combined_array = array1 + array2
# Show combined array
print("Combined array:", combined_array)
Output: 👇️
Combined array: [1, 2, 3, 4, 5, 6]
In this example, we use the + operator to combine array1 and array2 into a single array combined_array.
Using append() Function
We can use the append() function to combine arrays.
Suppose we have the following arrays:
# Create arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]
# Combine arrays
array1.append(array2)
# Show combined array
print("Combined array:", array1)
Output: 👇️
Combined array: [1, 2, 3, [4, 5, 6]]
In this example, we use the append() function to add array2 as a single element to array1.
Using extend() Function
We can use the extend() function to combine arrays.
Suppose we have the following arrays:
# Create arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]
# Combine arrays
array1.extend(array2)
# Show combined array
print("Combined array:", array1)
Output: 👇️
Combined array: [1, 2, 3, 4, 5, 6]
In this example, we use the extend() function to add each element of array2 to array1.
Using itertools.chain() Function
We can use the itertools.chain() function to combine arrays.
Suppose we have the following arrays:
import itertools
# Create arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]
# Combine arrays
combined_array = list(itertools.chain(array1, array2))
# Show combined array
print("Combined array:", combined_array)
Output: 👇️
Combined array: [1, 2, 3, 4, 5, 6]
In this example, we use the itertools.chain() function to combine array1 and array2 into a single array combined_array.
Conclusion
We can use the + operator, the extend() function, the append() function, and the itertools.chain() function to combine arrays in Python. These methods provide a convenient way to merge arrays.