Python doesn’t have a built-in array data type, however, there are modules you can use to work with arrays. This article describes how to add to an array using the array and the NumPy modules. The array module is useful when you need to create an array of integers and floating-point numbers. The NumPy module is useful when you need to do mathematical operations on an array.
In many cases, you can use List
to create arrays because List
provides flexibility, such as mixed data types, and still has all the characteristics of an array. Learn more about lists in Python.
Note: You can only add elements of the same data type to an array. Similarly, you can only join two arrays of the same data type.
With the array module, you can concatenate, or join, arrays using the +
operator and you can add elements to an array using the append()
, extend()
, and insert()
methods.
Syntax | Description |
---|---|
+ operator, x + y |
Returns a new array with the elements from two arrays. |
append(x) |
Adds a single element to the end of the array. |
extend(iterable) |
Adds a list, array, or other iterable to the end of array. |
insert(i, x) |
Inserts an element before the given index of the array. |
The following example demonstrates how to create a new array object by joining two arrays:
import array
# create array objects, of type integer
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
# print the arrays
print("arr1 is:", arr1)
print("arr2 is:", arr2)
# create a new array that contains all of the elements of both arrays
# and print the result
arr3 = arr1 + arr2
print("After arr3 = arr1 + arr2, arr3 is:", arr3)
The output is:
Outputarr1 is: array('i', [1, 2, 3])
arr2 is: array('i', [4, 5, 6])
After arr3 = arr1 + arr2, arr3 is: array('i', [1, 2, 3, 4, 5, 6])
The preceding example creates a new array that contains all the elements of the the given arrays.
The following example demonstrates how to add to an array using the append()
, extend()
, and insert()
methods:
import array
# create array objects, of type integer
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
# print the arrays
print("arr1 is:", arr1)
print("arr2 is:", arr2)
# append an integer to an array and print the result
arr1.append(4)
print("\nAfter arr1.append(4), arr1 is:", arr1)
# extend an array by appending another array of the same type
# and print the result
arr1.extend(arr2)
print("\nAfter arr1.extend(arr2), arr1 is:", arr1)
# insert an integer before index position 0 and print the result
arr1.insert(0, 10)
print("\nAfter arr1.insert(0, 10), arr1 is:", arr1)
The output is:
Outputarr1 is: array('i', [1, 2, 3])
arr2 is: array('i', [4, 5, 6])
After arr1.append(4), arr1 is: array('i', [1, 2, 3, 4])
After arr1.extend(arr2), arr1 is: array('i', [1, 2, 3, 4, 4, 5, 6])
After arr1.insert(0, 10), arr1 is: array('i', [10, 1, 2, 3, 4, 4, 5, 6])
In the preceding example, each method is called on the arr1
array object and modifies the original object.
With the NumPy module, you can use the NumPy append()
and insert()
functions to add elements to an array.
Syntax | Description |
---|---|
numpy.append(arr, values, axis=None) |
Appends the values or array to the end of a copy of arr . If the axis is not provided, then default is None , which means both arr and values are flattened before the append operation. |
numpy.insert(arr, obj, values, axis=None) |
Inserts the values or array before the index (obj ) along the axis. If the axis is not provided, then the default is None , which means that only arr is flattened before the insert operation. |
The numpy.append()
function uses the numpy.concatenate()
function in the background. You can use numpy.concatenate()
to join a sequence of arrays along an existing axis. Learn more about array manipulation routines in the NumPy documentation.
Note: You need to install NumPy to test the example code in this section.
The examples in this section use 2-dimensional (2D) arrays to highlight how the functions manipulate arrays depending on the axis value you provide.
numpy.append()
NumPy arrays can be described by dimension and shape. When you append values or arrays to multi-dimensional arrays, the array or values being appended need to be the same shape, excluding along the given axis.
To understand the shape of a 2D array, consider rows and columns. array([[1, 2], [3, 4]])
has a 2, 2
shape equivalent to 2 rows and 2 columns, while array([[10, 20, 30], [40, 50, 60]])
has a 2, 3
shape equivalent to 2 rows and 3 columns.
Test this concept using the Python interactive console.
First, import the NumPy module, then create some arrays and check their shape.
Import NumPy, then create and print np_arr1
:
- import numpy as np
- np_arr1 = np.array([[1, 2], [3, 4]])
- print(np_arr1)
Output[[1 2]
[3 4]]
Check the shape of np_arr1
:
- np_arr1.shape
Output(2, 2)
Create and print another array, np_arr2
:
- np_arr2 = np.array([[10, 20, 30], [40, 50, 60]])
- print(np_arr2)
Output[[10 20 30]
[40 50 60]]
Check the shape of np_arr2
:
- np_arr2.shape
Output(2, 3)
Then try appending arrays along the different axes. You can append an array with a shape of 2, 3
to an array with a shape of 2, 2
along axis 1
, but not along axis 0
.
Append np_arr2
to np_arr1
along axis 0, or by row:
- np.append(np_arr1, np_arr2, axis=0)
You get a ValueError
:
OutputTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 5, in append
File "/Users/digitalocean/opt/anaconda3/lib/python3.9/site-packages/numpy/lib/function_base.py", line 4817, in append
return concatenate((arr, values), axis=axis)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 3
You can’t append an array with rows that are three columns wide to an array with rows that are only two columns wide.
Append np_arr2
to np_arr1
along axis 1, or by column:
- np.append(np_arr1, np_arr2, axis=1)
The output is:
Outputarray([[ 1, 2, 10, 20, 30],
[ 3, 4, 40, 50, 60]])
You can append an array with columns that are two rows high to another array with columns that are two rows high.
The following example demonstrates how to add elements to a NumPy array using the numpy.append()
function:
import numpy as np
# create 2D array objects (integers)
np_arr1 = np.array([[1, 2], [3, 4]])
np_arr2 = np.array([[10, 20], [30, 40]])
# print the arrays
print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)
# append an array to the end of another array and print the result
# both arrays are flattened before appending
append_axis_none = np.append(np_arr1, np_arr2, axis=None)
print("append_axis_none is:\n", append_axis_none)
# append an array to the end of another array along axis 0 (append rows)
# and print the result
append_axis_0 = np.append(np_arr1, np_arr2, axis=0)
print("append_axis_0 is:\n", append_axis_0)
# append an array to the end of another array along axis 1 (append columns)
# and print the result
append_axis_1 = np.append(np_arr1, np_arr2, axis=1)
print("append_axis_1 is:\n", append_axis_1)
The output is:
Outputnp_arr1 is:
[[1 2]
[3 4]]
np_arr2 is:
[[10 20]
[30 40]]
append_axis_none is:
[ 1 2 3 4 10 20 30 40]
append_axis_0 is:
[[ 1 2]
[ 3 4]
[10 20]
[30 40]]
append_axis_1 is:
[[ 1 2 10 20]
[ 3 4 30 40]]
The preceding example shows how the numpy.append()
function works for each axis of the 2D array and how the shape of the resulting array changes. When the axis is 0
, the array is appended by row. When the axis is 1
, the array is appended by column.
numpy.insert()
The numpy.insert()
function inserts an array or values into another array before the given index, along an axis, and returns a new array.
Unlike the numpy.append()
function, if the axis is not provided or is specified as None
, the numpy.insert()
function flattens only the first array, and does not flatten the values or array to be inserted. You’ll get a ValueError
if you attempt to insert a 2D array into a 2D array without specifying an axis.
The following example demonstrates how to insert elements into an array using the numpy.insert()
function:
import numpy as np
# create array objects (integers)
np_arr1 = np.array([[1, 2], [4, 5]])
np_arr2 = np.array([[10, 20], [30, 40]])
np_arr3 = np.array([100, 200, 300])
# print the arrays
print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)
print("np_arr3 is:\n", np_arr3)
# insert a 1D array into a 2D array and then print the result
# the original array is flattened before insertion
insert_axis_none = np.insert(np_arr1, 1, np_arr3, axis=None)
print("insert_axis_none is:\n", insert_axis_none)
# insert an array into another array by row
# and print the result
insert_axis_0 = np.insert(np_arr1, 1, np_arr2, axis=0)
print("insert_axis_0 is:\n", insert_axis_0)
# insert an array into another array by column
# and print the result
insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1)
print("insert_axis_1 is:\n", insert_axis_1)
The output is:
Outputnp_arr1 is:
[[1 2]
[4 5]]
np_arr2 is:
[[10 20]
[30 40]]
insert_axis_none is:
[ 1 100 200 300 2 4 5]
insert_axis_0 is:
[[ 1 2]
[10 20]
[30 40]
[ 4 5]]
insert_axis_1 is:
[[ 1 10 30 2]
[ 4 20 40 5]]
In the preceding example, when you inserted a 2D array into another 2D array along axis 1, each array within np_arr2
was inserted as a separate column into np_arr1
. If you want to insert the whole 2D array into another 2D array, include square brackets around the obj
parameter index value to indicate that the whole array should be inserted before that position. Without the square brackets, numpy.insert()
stacks the arrays in sequence as columns before the given index.
The following example shows the output with and without square brackets around the obj
(index) parameter:
import numpy as np
# create 2D array objects (integers)
np_arr1 = np.array([[1, 2], [3, 4]])
np_arr2 = np.array([[10, 20], [30, 40]])
# print the arrays
print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)
# insert an array, column by column, into another array
# and print the result
insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1)
print("insert_axis_1 is:\n", insert_axis_1)
# insert a whole array into another array by column
# and print the result
insert_index_axis_1 = np.insert(np_arr1, [1], np_arr2, axis=1)
print("insert_index_axis_1 is:\n", insert_index_axis_1)
The output is:
Outputnp_arr1 is:
[[1 2]
[3 4]]
np_arr2 is:
[[10 20]
[30 40]]
insert_axis_1 is:
[[ 1 10 30 2]
[ 3 20 40 4]]
insert_index_axis_1 is:
[[ 1 10 20 2]
[ 3 30 40 4]]
The preceding example shows how numpy.insert()
inserts columns into an array depending on the index notation.
In this article you added elements to arrays using the array and NumPy modules. Continue your learning with more NumPy tutorials and Python tutorials.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
all we want to do is something really simple like somarray = [0] * 256 somearray[5] = 100 but it will throw list index out of range, even after it was created with the right size why cant you just write simple solution to this problem
- kop
How can I insert element at given position by using array module without using any in built function in python
- Mohanish
Thank you! very helpful
- Jul