Python - Add Array Items
Python 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.
Adding Elements to Python Array
There are multiple ways to add elements to an array in Python −
- Using append() method
- Using insert() method
- Using extend() method
Using append() method
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.
Syntax
Syntax of the append() method is as follows −
append(v)
Where,
Example
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)
It will produce the following output −
array('i', [1, 2, 3, 10])
Using insert() method
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.
Syntax
Syntax of this method is shown below −
insert(i, v)
Where,
Example
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)
It will produce the following output −
array('i', [1, 20, 2, 3])
Using extend() method
The extend() method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.
Syntax
This method has the following syntax −
extend(x)
Where,
Example
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)
On executing the above code, it will produce the following output −
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])