Python Add Array Item
If we're working with arrays in Python, we might often need to add items to an array. In this article, we’ll explore how to add items to an array using different methods.
Add single element - Using append()
The append() method adds a single element to the end of the array. This is one of the most straightforward ways to add an item to an array in Python.
import array
# Create an array
arr = array.array('i', [1, 2, 3])
# Add an item using append()
arr.append(4)
print(arr)
Output
array('i', [1, 2, 3, 4])
Let's explore other methods of adding item in array :
Add multiple items - Using extend()
If we want to add multiple items to an array at once, you can use the extend() method. This method adds each item from an iterable (like a list or another array) to the array.
import array
# Create an array
arr = array.array('i', [1, 2, 3])
# Add multiple items using extend
arr.extend([4, 5, 6])
print(arr)
Output
array('i', [1, 2, 3, 4, 5, 6])
Add item at position - Using insert()
The insert() method allows us to add an element at any position in the array. We specify the index where we want to insert the new element.
import array
# Create an array
arr = array.array('i', [1, 2, 4, 5])
# Insert an item at index 2
arr.insert(2, 3)
print(arr)
Output
array('i', [1, 2, 3, 4, 5])
Using Slicing and Assignment
Another way to add items to an array is by using slicing. We can assign new values to a slice of the array, effectively adding items at any position.
import array
# Create an array
arr = array.array('i', [1, 2, 4, 5])
# Add an item at index 2 using slicing
arr[2:2] = array.array('i', [3]) # Convert the list to an array
print(arr)
Output
array('i', [1, 2, 3, 4, 5])
Using + Operator (Concatenation)
Although this isn’t the most efficient method for adding a single item, we can concatenate arrays using the + operator. This method is typically used to join two arrays but it can also be used to add a new item.
import array
# Create an array
arr = array.array('i', [1, 2, 3])
# Add an item using concatenation
arr = arr + array.array('i', [4])
print(arr)
Output
array('i', [1, 2, 3, 4])
Using array() Constructor with + Operator
If we are adding multiple items or even replacing the entire array, we can recreate the array using the array() constructor and the + operator.
import array
# Create two arrays
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
# Concatenate using the + operator
arr = arr1 + arr2
print(arr)
Output
array('i', [1, 2, 3, 4, 5, 6])