What is the method for concatenating arrays in Python?
There are multiple ways to concatenate arrays in Python. Here are some commonly used methods:
- Using the “+” operator: You can use the “+” operator to concatenate two arrays together.
array1 = [1, 2, 3]
array2 = [4, 5, 6]
result = array1 + array2
print(result) # 输出:[1, 2, 3, 4, 5, 6]
- You can append the elements of one array to another array using the extend() method.
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array1.extend(array2)
print(array1) # 输出:[1, 2, 3, 4, 5, 6]
- Using the append() method: You can add an entire array as a single element to the end of another array using the append() method.
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array1.append(array2)
print(array1) # 输出:[1, 2, 3, [4, 5, 6]]
It is important to note that using the append() method adds the entire array as an element to another array, rather than adding the elements of the array to another array. To merge two arrays into one, you can use the extend() method or the “+” operator.