Python add to Array

Filed Under: Python
Python Add To Array

Python doesn’t have any specific data type as an array. We can use List that has all the characteristics of an array.

Python array module can be used to create an array of integers and floating-point numbers.

If you want to do some mathematical operations on an array, you should use the NumPy module.

1. Python add to Array

  • If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List.
  • If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.
  • If you are using NumPy arrays, use the append() and insert() function.

2. Adding elements to an Array using array module

  • Using + operator: a new array is returned with the elements from both the arrays.
  • append(): adds the element to the end of the array.
  • insert(): inserts the element before the given index of the array.
  • extend(): used to append the given array elements to this array.

import array

arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])

print(arr1)  # array('i', [1, 2, 3])
print(arr2)  # array('i', [4, 5, 6])

arr3 = arr1 + arr2
print(arr3)  # array('i', [1, 2, 3, 4, 5, 6])

arr1.append(4)
print(arr1)  # array('i', [1, 2, 3, 4])

arr1.insert(0, 10)
print(arr1)  # array('i', [10, 1, 2, 3, 4])

arr1.extend(arr2)
print(arr1)  # array('i', [10, 1, 2, 3, 4, 4, 5, 6])

3. Adding elements to the NumPy Array

  • append(): the given values are added to the end of the array. If the axis is not provided, then the arrays are flattened before appending.
  • insert(): used to insert values at the given index. We can insert elements based on the axis, otherwise, the elements will be flattened before the insert operation.

>>> import numpy as np
>>> np_arr1 = np.array([[1, 2], [3, 4]])
>>> np_arr2 = np.array([[10, 20], [30, 40]])
>>> 
>>> np.append(np_arr1, np_arr2)
array([ 1,  2,  3,  4, 10, 20, 30, 40])
>>>
>>> np.append(np_arr1, np_arr2, axis=0)
array([[ 1,  2],
       [ 3,  4],
       [10, 20],
       [30, 40]])
>>>
>>> np.append(np_arr1, np_arr2, axis=1)
array([[ 1,  2, 10, 20],
       [ 3,  4, 30, 40]])
>>> 
>>> np.insert(np_arr1, 1, np_arr2, axis=0)
array([[ 1,  2],
       [10, 20],
       [30, 40],
       [ 3,  4]])
>>> 
>>> np.insert(np_arr1, 1, np_arr2, axis=1)
array([[ 1, 10, 30,  2],
       [ 3, 20, 40,  4]])
>>> 

4. References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages