Tutorial

Python Array Add: How to Append, Extend & Insert Elements

Updated on April 15, 2025
Python Array Add: How to Append, Extend & Insert Elements

Introduction

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.

Adding Elements to an Array Using the Array Module

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:

Output
arr1 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:

Output
arr1 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.

Adding Elements to a NumPy Array

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.

Appending to an Array using 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:

  1. import numpy as np
  2. np_arr1 = np.array([[1, 2], [3, 4]])
  3. print(np_arr1)
Output
[[1 2] [3 4]]

Check the shape of np_arr1:

  1. np_arr1.shape
Output
(2, 2)

Create and print another array, np_arr2:

  1. np_arr2 = np.array([[10, 20, 30], [40, 50, 60]])
  2. print(np_arr2)
Output
[[10 20 30] [40 50 60]]

Check the shape of np_arr2:

  1. 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:

  1. np.append(np_arr1, np_arr2, axis=0)

You get a ValueError:

Output
Traceback (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:

  1. np.append(np_arr1, np_arr2, axis=1)

The output is:

Output
array([[ 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:

Output
np_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.

Adding to an Array using 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:

Output
np_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:

Output
np_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.

Performance comparison: append(), extend(), insert(), and NumPy operation

Method Description Advantages Disadvantages Usage Example Performance
append() Adds a single element to the end of the array. Easy to use, efficient for adding single elements. Not suitable for adding multiple elements at once. Adding a single element to the end of an array. arr.append(5) O(1)
extend() Adds multiple elements to the end of the array. Allows adding multiple elements at once. Can be inefficient for large lists due to memory reallocation. Adding multiple elements to the end of an array. arr.extend([5, 6, 7]) O(k), where k is the number of elements to extend
insert() Inserts an element at a specified position in the array. Allows inserting elements at specific positions. Can be inefficient for large lists, especially when inserting at the beginning, due to shifting elements. Inserting an element at a specific position in an array. arr.insert(2, 5) O(n), where n is the size of the array
numpy.append() Appends values or an array to the end of a copy of the array. Supports multi-dimensional arrays, allows appending along specific axes. Creates a copy of the original array, can be inefficient for large arrays due to memory allocation. Appending to a multi-dimensional array along a specific axis. np.append(arr, [5, 6], axis=1) O(n), where n is the size of the array
numpy.insert() Inserts values or an array before a specified index along a specified axis. Supports multi-dimensional arrays, allows inserting along specific axes. Creates a copy of the original array, can be inefficient for large arrays due to memory allocation. Inserting into a multi-dimensional array along a specific axis. np.insert(arr, 2, [5, 6], axis=1) O(n), where n is the size of the array

Common Errors and Debugging

Error: Using append() instead of extend() for multiple elements

When you need to add multiple elements to an array, using append() instead of extend() can lead to unexpected results. append() adds a single element to the end of the array, while extend() adds multiple elements from an iterable to the end of the array.

Error Code Snippet:

arr = [1, 2, 3]
arr.append([4, 5, 6])  # Using append() for multiple elements
print(arr)  # Output: [1, 2, 3, [4, 5, 6]]

Why it occurs: This error occurs because append() treats the list [4, 5, 6] as a single element and adds it to the end of the array, resulting in a nested list structure.

How to fix it:

To fix this error, use extend() instead of append() when adding multiple elements to an array. extend() will add each element from the iterable to the end of the array, resulting in a flat list structure.

arr = [1, 2, 3]
arr.extend([4, 5, 6])  # Using extend() for multiple elements
print(arr)  # Output: [1, 2, 3, 4, 5, 6]

By using extend(), you ensure that each element from the iterable is added individually to the end of the array, resulting in the expected flat list structure.

Error: Type mismatch when working with NumPy arrays

When working with NumPy arrays, it’s essential to ensure that the data types of the elements being added match the data type of the array. A type mismatch can lead to unexpected behavior, errors, or even silent failures.

Error Code Snippet:

import numpy as np

arr = np.array([1, 2, 3], dtype=int)  # Array with integer data type
arr = np.append(arr, [4.5, 6.7])  # Attempting to append float values
print(arr)  # Output: [1.  2.  3.  4.5 6.7], data type changed to float

Why it occurs: This error occurs because NumPy arrays are designed to store elements of a single data type. When you try to add elements of a different data type, NumPy will silently convert the entire array to a data type that can accommodate the new elements, potentially leading to loss of precision or unexpected behavior.

How to fix it: To fix this error, ensure that the data types of the elements being added match the data type of the array. If necessary, convert the elements to the correct data type before adding them to the array.

import numpy as np

arr = np.array([1, 2, 3], dtype=int)  # Array with integer data type
arr = np.append(arr, [4, 6])  # Adding integer values to maintain data type consistency
print(arr)  # Output: [1 2 3 4 6], data type remains integer

By ensuring data type consistency, you can avoid type mismatch errors and ensure predictable behavior when working with NumPy arrays.

Error: Trying to add elements to a tuple (which is immutable)

This error occurs because tuples are immutable data structures in Python, meaning their contents cannot be modified after creation. Attempting to add elements to a tuple will result in a TypeError.

Error Code Snippet:

# Attempting to add an element to a tuple
my_tuple = (1, 2, 3)
my_tuple.append(4)  # This will raise a TypeError
print(my_tuple)  # This line will not be executed due to the TypeError

How to fix it:

To fix this error, use a mutable data structure like a list instead of a tuple. Lists can be modified after creation, allowing you to add or remove elements as needed.

# Using a list instead of a tuple
my_list = [1, 2, 3]
my_list.append(4)  # This is allowed
print(my_list)  # Output: [1, 2, 3, 4]

By using a list, you can dynamically add or remove elements, ensuring that your code is flexible and error-free.

FAQs

1. How to add to an array in Python?

To add elements to an array in Python, you can use the append() method for single elements or the extend() method for multiple elements. Here’s an example using the array module:

import array

arr = array.array('i', [1, 2, 3])  # Create an array
arr.append(4)  # Add a single element
arr.extend([5, 6])  # Add multiple elements
print(arr)  # Output: array('i', [1, 2, 3, 4, 5, 6])

2. How do you sum an array in Python?

To sum an array in Python, you can use the sum() function. Here’s an example:

arr = [1, 2, 3, 4, 5, 6]  # Create a list (not an array, but works similarly)
total = sum(arr)  # Sum the elements
print(total)  # Output: 21

3. How do you add each element in an array in Python?

To add each element in an array in Python, you can use a loop or the sum() function as shown in the previous answer. Here’s an example using a loop:

arr = [1, 2, 3, 4, 5, 6]  # Create a list (not an array, but works similarly)
total = 0  # Initialize a variable to hold the sum
for element in arr:  # Iterate over the array
    total += element  # Add each element to the total
print(total)  # Output: 21

4. What is the difference between a Python list and an array?

In Python, a list is a built-in data structure that can hold elements of different data types, including strings, integers, floats, and other lists. Lists are dynamic, meaning they can grow or shrink as elements are added or removed. They are also mutable, meaning their contents can be modified after creation.

An array, on the other hand, is a data structure that can be created using the array module in Python. Arrays are similar to lists but are more restrictive in terms of the data types they can hold. They are designed to work with large amounts of numerical data and are more efficient in terms of memory usage. Arrays are also mutable, but they are not dynamic in the same way as lists.

Here’s an example of creating a list and an array:

# Create a list
list_example = [1, 2, 3, "four", 5.0]  # Lists can hold different data types
print(list_example)  # Output: [1, 2, 3, 'four', 5.0]

# Create an array
import array
array_example = array.array('i', [1, 2, 3, 4, 5])  # Arrays are type-specific
print(array_example)  # Output: array('i', [1, 2, 3, 4, 5])

5. How do I add two arrays in Python?

To add two arrays in Python, you can use the + operator if you’re working with lists or the extend() method if you’re working with arrays from the array module. Here are examples of both:

# Adding two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result_list = list1 + list2  # Using the + operator
print(result_list)  # Output: [1, 2, 3, 4, 5, 6]

# Adding two arrays
import array
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
arr1.extend(arr2)  # Using the extend method
print(arr1)  # Output: array('i', [1, 2, 3, 4, 5, 6])

6. What is the fastest way to add elements to an array?

The fastest way to add elements to an array in Python depends on the context and the type of array you’re working with. If you’re working with a list, the append() method is generally the fastest way to add a single element. If you need to add multiple elements, the extend() method is faster than calling append() multiple times.

If you’re working with an array from the array module, the extend() method is the fastest way to add elements.

Here’s a comparison of the performance of append() and extend() for lists:

import timeit

# Create a list
list_example = []

# Timing append()
start_time = timeit.default_timer()
for i in range(10000):
    list_example.append(i)
end_time = timeit.default_timer()
print(f"Time taken by append(): {end_time - start_time} seconds")

# Timing extend()
list_example = []
start_time = timeit.default_timer()
list_example.extend(range(10000))
end_time = timeit.default_timer()
print(f"Time taken by extend(): {end_time - start_time} seconds")

Output:

Time taken by append(): 0.012 seconds
Time taken by extend(): 0.006 seconds

The output shows that extend() is generally faster than append() for adding multiple elements to a list.

Conclusion

In this tutorial, you learned how to add elements to arrays using the array and NumPy modules. You explored the append(), extend(), and insert() methods for the array module, and the append() and insert() functions for the NumPy module. You also learned about the performance comparison of these methods and functions.

To continue your learning, check out these Python tutorials:

Happy coding!

Continue building with DigitalOcean Gen AI Platform.

About the author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 5, 2020

Thank you! very helpful

- Jul

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 2, 2020

    How can I insert element at given position by using array module without using any in built function in python

    - Mohanish

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 9, 2021

      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

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Become a contributor for community

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        DigitalOcean Documentation

        Full documentation for every DigitalOcean product.

        Resources for startups and SMBs

        The Wave has everything you need to know about building a business, from raising funding to marketing your product.

        Get our newsletter

        Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

        New accounts only. By submitting your email you agree to our Privacy Policy

        The developer cloud

        Scale up as you grow — whether you're running one virtual machine or ten thousand.

        Get started for free

        Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

        *This promotional offer applies to new accounts only.