Adding Items to Arrays in Python: Methods and Techniques
Discover how to add items to Python arrays using various methods like append()
, insert()
, and extend()
. This guide explains how to manipulate and combine arrays with practical examples and code snippets.
Python - Add Array Items
Python arrays are mutable sequences, meaning they can be changed. Items of the same data type can be added to an array. You can also join two arrays of the same data type.
Python uses the array
module for array functionality.
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
The append()
method adds a new element at the end of an array. It accepts a single item as an argument.
Syntax
import array as arr
a = arr.array('i', [1, 2, 3])
a.append(10)
print(a)
Output
array('i', [1, 2, 3, 10])
Using insert()
Method
The insert()
method adds a new element at a specified index. It accepts two parameters: the index and the value.
Syntax
import array as arr
a = arr.array('i', [1, 2, 3])
a.insert(1, 20)
print(a)
Output
array('i', [1, 20, 2, 3])
Using extend()
Method
The extend()
method adds all elements from an iterable or another array of the same data type.
Syntax
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])