How to Append Element to Array in Python
To append an element to an array in Python, you can use two different methods.
The following examples show how to append an element to an array in Python.
Appending Array using Numpy
We can use the numpy library to append elements to an array.
Suppose we have the following arrays:
# Import numpy library
import numpy as np
# Declare arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Append arrays
arr3 = np.concatenate((arr1, arr2))
# Show new array
print("Appended array:", arr3)
Output: 👇️
Appended array: [1 2 3 4 5 6]
In this example, we use the concatenate() function from the numpy library to append arr2 to arr1.
Appending Array using List
We can also append an array as a list using the append() function.
Suppose we have the following list:
# Declare list
my_list = [1, 2, 3]
# Add elements
my_list.append([4, 5, 6])
# Show updated list
print("Updated list:", my_list)
Output: 👇️
Updated list: [1, 2, 3, [4, 5, 6]]
In this example, we use the append() function to add the list [4, 5, 6] to my_list.