Table of Contents
TogglePython array is a mutable sequence which means they can be changed or modified whenever required. However, items of same data type can be added to an array. In the similar way, you can only join two arrays of the same data type.
Python does not have built-in support for arrays, it uses array module to achieve the functionality like an array.
There are multiple ways to add elements to an array in Python −
To add a new element to an array, use the append() method. It accepts a single item as an argument and append it at the end of given array.
append(v)
Where,
v − new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.
Here, we are adding element at the end of specified array using append() method.
import array as arr
a = arr.array('i', [1, 2, 3])
a.append(10)
print(a)
Output: array(‘i’, [1, 2, 3, 10])
It is possible to add a new element at the specified index using the insert() method. The array module in Python defines this method. It accepts two parameters which are index and value and returns a new array after adding the specified value.
insert(i, v)
Where,
i − The index at which new value is to be inserted.
v − The value to be inserted. Must be of the arraytype.
The following example shows how to add array elements at specific index with the help of insert() method.
import array as arr
a = arr.array('i', [1, 2, 3])
a.insert(1, 20)
print(a)
Output: array(‘i’, [1, 20, 2, 3])
The extend() method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.
extend(x)
Where,
x − This parameter specifies an array or iterable.
In this example, we are adding items from another array to the specified array.
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5])
b = arr.array('i', [6, 7, 8, 9, 10])
a.extend(b)
print(a)
Output: array(‘i’, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Key Takeaway: Add items to arrays with append() (end), insert() (specific index), or extend() (multiple items)—flexible tools for array growth!
