Learning Center
Python

How to Add Elements to an Array in Python

18 Dec 2024
Anees Asghar
Anees Asghar

In Python, inserting items into arrays is a frequent task. Arrays hold data of a single type and can be initialized with lists, the array module, or through NumPy. Although Python lacks a native array type, both the array module and the NumPy library offer flexible options for managing arrays. Each approach provides unique methods for inserting elements, based on specific needs.

Functions such as append() and extend() allow us to add items to built-in arrays. List comprehension is helpful for generating new arrays. For more complex tasks, NumPy offers tools like append(), concatenate(), and insert() to add elements, particularly when dealing with numerical or structured data. Each approach is useful for specific situations.

In this tutorial, we will demonstrate all available techniques for inserting elements into an array in Python.

Adding Values to Python's Inbuilt Arrays
Copy link

Python provides different methods for inserting values into its inbuilt arrays. These functions allow us to add items at the start, end, or a specific array position. Let’s go through the following methods to understand how they work and which one fits your needs.

Method 1: array.append()
Copy link

append() is a useful array method that lets us insert a single value at the last index of the target array. It modifies the original array:

from array import array 

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
print("Modified Array: ")
AuthorsIDs.append(140)
print(AuthorsIDs)

Initially, the AuthorIDs array has 12, 110, and 13 as its elements. Next, we invoke append() on the AuthorIDs array to insert 140 at the last position:

Image4

Here, we utilize i to assign signed integers to AuthorIDs. Similarly, users can specify type codes like f, u, d, etc. to assign float, Unicode, and double-type data to an array.

Method 2: array.extend()
Copy link

Array module offers another useful function extend() that lets us add numerous items at the end of an array. It expands the actual array:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
AuthorsIDs.extend([19, 105, 16])
print("Modified Array: ")
print(AuthorsIDs)

This time, we extend AuthorsIDs with a sub-array of three items:

Image6

Method 3: array.insert()
Copy link

insert() is an inbuilt array function that lets us add values at an index of our choice and shift the subsequent entries accordingly. It accepts two arguments a value to be added and an index at which the value will be placed:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
AuthorsIDs.insert(2, 55)
print("Modified Array: ")
print(AuthorsIDs)

Here, we add 55 at the third index of AuthorIDs:

Image5

Method 4: List Comprehension
Copy link

List comprehension lets us integrate new values with existing ones to create an updated array. It doesn’t alter the actual array; instead, it generates a new array based on the given logic:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
newIDs = [14, 51]
AuthorsIDs = array('i', [x for x in AuthorsIDs] + newIDs)
print("Modified Array: ")
print(AuthorsIDs)  

The newIDs are successfully merged with the AuthorIDs through list comprehension:

Image8

Method 5: Plus Operator
Copy link

The plus operator + joins the provided arrays. It enables us to add one or more values to the target array:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
newIDs = array('i', [14, 51, 72])
totalIDs = AuthorsIDs + newIDs 
print("Modified Array: ")
print(totalIDs) 

The + operator successfully integrates the AuthorsIDs and newIDs arrays while preserving the initial ones:

Image7

Add Elements to NumPy Array
Copy link

NumPy is a commonly utilized Python library in data science and numerical computing. It aids in handling arrays and executing arithmetic operations. Various functions, including append(), concatenate(), and insert(), can be employed to add values to NumPy arrays.

Method 1: numpy.append()
Copy link

The append() method of the numpy module adds elements at the end of an array and retrieves a new array. It lets us insert one or more values to a numpy array. Let's import the NumPy library and invoke append() to add the desired elements to the last of AuthorIDs:

import numpy as npy

AuthorsIDs = npy.array([12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
updatedIDs = npy.append(AuthorsIDs, [140, 31])

print("Modified Array: ")
print(updatedIDs)

It successfully appends 140 and 31 at the right/last of AuthorsIDs:

Image2

Method 2: numpy.concatenate()
Copy link

NumPy offers a very useful function named concatenate() that merges multiple numpy arrays. Let’s invoke the concatenate() function to integrate the AuthorIDs with newIDs array:

import numpy as npy

AuthorsIDs = npy.array([12, 110, 13])
newIDs = npy.array([101, 1, 31])
concatenatedIDs = npy.concatenate((AuthorsIDs, newIDs))
print("Modified Array: ")
print(concatenatedIDs)

We store the concatenated values in a new array named concatenatedIDs:

Image1

Method 3: numpy.insert()
Copy link

The numpy.insert() function provides the flexibility to place one or more values at any given index of the target array:

import numpy as npy

AuthorsIDs = npy.array([1, 103, 41])
print("Original Array: ")
print(AuthorIDs)
newIDs = npy.insert(AuthorsIDs, 1, 102)
print("Modified Array: ")
print(newIDs)

It successfully appended 102 at the first index of AuthorsIDs:

Image3

Best Practices
Copy link

When managing arrays in Python, the append() method is utilized to insert a single value to the final index of the array. To include multiple elements, you can employ extend() or the + operator. Additionally, the insert() method enables adding elements at specific positions within the array, making it versatile for various use cases.

In contrast, NumPy arrays offer more specialized functions for managing data efficiently. numpy.append() is used for appending data, while numpy.concatenate() merges multiple arrays. numpy.insert() can be used for precise insertions.

NumPy functions are generally preferred for tasks involving large datasets or numerical computations due to their better performance and scalability.

Conclusion
Copy link

In this tutorial, we demonstrated distinct inbuilt and numpy functions for appending elements to Python arrays.

Users can utilize several methods to append values to Python arrays, based on the array type and specific use case. For inbuilt arrays, append(), extend(), and insert() allow easy modifications, while list comprehension and the + operator provide additional flexibility for merging arrays. 

When operating with NumPy arrays, append(), concatenate(), and insert() offer advanced functionality, especially for quantitative and data science tasks. For larger datasets or more complex operations, you should prefer NumPy due to its efficiency and performance. 

If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.