Report this

What is the reason for this report?

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

Updated on June 12, 2026
Python Array Add: How to Append, Extend & Insert Elements

Introduction

To add to an array in Python, you append, extend, or insert elements depending on the structure you use. Most tutorials mean a Python list when they say “array.” For typed numeric storage, use the stdlib array module. For math on multi-dimensional data, use NumPy.

nums = [1, 2, 3]
nums.append(4)           # one item at the end
nums.extend([5, 6])      # many items at the end
nums.insert(0, 0)        # one item at an index
print(nums)              # [0, 1, 2, 3, 4, 5, 6]

This guide covers lists, the array module, and NumPy. You will see when to pick each type, how to add elements in a loop, and how to avoid common production errors.

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Key takeaways

  • Lists are the default “array” in Python. Use append() for one item, extend() for many, and insert() for a specific index.
  • The array module stores one numeric type per array. append(), extend(), and insert() work like lists, and + joins two arrays into a new object.
  • NumPy returns a new array from numpy.append() and numpy.insert(). The original array stays unchanged.
  • append() vs extend(): append() adds one object. extend() unpacks an iterable and adds each value. Mixing them up creates nested lists.
  • Shape matters for 2D NumPy arrays. Row and column widths must match along the axis you choose, or Python raises ValueError.
  • For repeated growth in loops, extend() or numpy.concatenate() beat many single-item appends on large data sets.
  • Tuples are immutable. Convert to a list before you add elements.

Prerequisites

Python list vs array module vs NumPy

Structure Built-in / package Mixed types Best for
list Built-in Yes General sequences, APIs, mixed data
array.array stdlib array No Compact numeric buffers
numpy.ndarray NumPy No Math, ML, multi-dimensional data

Note: You only add elements of the same data type to an array.array object. You only join two array.array objects with matching type codes.

Add elements to a Python list

Most “add to array” searches target lists. Lists are mutable and accept mixed types. See Python Add to List for a full walkthrough.

Method Behavior Example
append(x) Adds one item to the end nums.append(4)
extend(iterable) Adds each item from an iterable nums.extend([5, 6])
insert(i, x) Inserts one item before index i nums.insert(0, 10)
+ operator Returns a new combined list nums = a + b
nums = [1, 2, 3]

nums.append(4)
print(nums)                 # [1, 2, 3, 4]

nums.extend([5, 6])
print(nums)                 # [1, 2, 3, 4, 5, 6]

nums.insert(0, 0)
print(nums)                 # [0, 1, 2, 3, 4, 5, 6]

more = nums + [7, 8]
print(more)                 # [0, 1, 2, 3, 4, 5, 6, 7, 8]

For list-specific methods, see How to Use List Methods in Python 3.

Add elements in a loop

You often build a sequence while iterating. append() adds one value per trip through the loop. extend() adds a batch when you already have a collection.

squares = []
for n in range(5):
    squares.append(n ** 2)
print(squares)              # [0, 1, 4, 9, 16]

For a compact alternative, use a list comprehension:

squares = [n ** 2 for n in range(5)]
print(squares)              # [0, 1, 4, 9, 16]

Inside a for loop, call extend() when each iteration produces multiple values:

rows = []
for pair in [(1, 2), (3, 4)]:
    rows.extend(pair)
print(rows)                 # [1, 2, 3, 4]

Adding elements with the array module

The array module stores integers, floats, or other numeric codes in a compact buffer. You join arrays with + or mutate in place with append(), extend(), and insert().

Syntax Description
+ operator, x + y Returns a new array with elements from both arrays
append(x) Adds a single element to the end
extend(iterable) Adds items from a list, array, or other iterable
insert(i, x) Inserts an element before index i

The following example creates a new array by joining two arrays:

import array

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

print("arr1 is:", arr1)
print("arr2 is:", arr2)

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 next example adds elements with append(), extend(), and insert():

import array

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

print("arr1 is:", arr1)
print("arr2 is:", arr2)

arr1.append(4)
print("\nAfter arr1.append(4), arr1 is:", arr1)

arr1.extend(arr2)
print("\nAfter arr1.extend(arr2), arr1 is:", arr1)

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])

Each method runs on arr1 and changes the original object.

Adding elements to a NumPy array

NumPy provides numpy.append() and numpy.insert() for adding values. Both return a copy. Neither changes the source array. For frequent updates, prefer numpy.concatenate() or pre-allocate with numpy.zeros() and assign by index.

Syntax Description
numpy.append(...) Appends to a copy. axis=None flattens both.
numpy.insert(...) Inserts before index. axis=None flattens arr.

numpy.append() calls numpy.concatenate() internally. See array manipulation routines in the NumPy docs. For a focused guide, read NumPy Append in Python.

Note: Install NumPy before you run the examples in this section. Follow the NumPy install guide.

The examples below use 2D arrays to show how the axis argument changes the result. Test them in the Python interactive console.

Appending with numpy.append()

NumPy arrays have a shape (rows, columns for 2D data). When you append along an axis, widths along the other dimensions must match.

array([[1, 2], [3, 4]]) has shape (2, 2). array([[10, 20, 30], [40, 50, 60]]) has shape (2, 3).

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 np_arr2:

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

Append np_arr2 to np_arr1 along axis 0 (by row):

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

You get a ValueError because the column counts differ (2 vs 3):

Output
Traceback (most recent call last): ... 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

Append along axis 1 (by column) instead:

  1. np.append(np_arr1, np_arr2, axis=1)
Output
array([[ 1, 2, 10, 20, 30], [ 3, 4, 40, 50, 60]])

When both arrays share the same row count, axis 1 works.

This script shows all three axis modes:

import numpy as np

np_arr1 = np.array([[1, 2], [3, 4]])
np_arr2 = np.array([[10, 20], [30, 40]])

print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)

append_axis_none = np.append(np_arr1, np_arr2, axis=None)
print("append_axis_none is:\n", append_axis_none)

append_axis_0 = np.append(np_arr1, np_arr2, axis=0)
print("append_axis_0 is:\n", append_axis_0)

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]]

With axis=0, rows stack. With axis=1, columns join. With axis=None, both arrays flatten into one 1D result.

Inserting with numpy.insert()

numpy.insert() places values before a given index along an axis and returns a new array. When axis=None, only the first array flattens. The values to insert keep their shape unless you pass an axis.

import numpy as np

np_arr1 = np.array([[1, 2], [4, 5]])
np_arr2 = np.array([[10, 20], [30, 40]])
np_arr3 = np.array([100, 200, 300])

print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)
print("np_arr3 is:\n", np_arr3)

insert_axis_none = np.insert(np_arr1, 1, np_arr3, axis=None)
print("insert_axis_none is:\n", insert_axis_none)

insert_axis_0 = np.insert(np_arr1, 1, np_arr2, axis=0)
print("insert_axis_0 is:\n", insert_axis_0)

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]] np_arr3 is: [100 200 300] 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]]

When you insert a 2D array along axis 1, each row of the inserted array becomes a separate column. Wrap the index in square brackets to insert the whole block at once:

import numpy as np

np_arr1 = np.array([[1, 2], [3, 4]])
np_arr2 = np.array([[10, 20], [30, 40]])

print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)

insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1)
print("insert_axis_1 is:\n", insert_axis_1)

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]]

insert_axis_1 interleaves columns. insert_index_axis_1 places the full np_arr2 block before column index 1.

append() vs extend()

Method Adds Result when you pass [4, 5, 6] to [1, 2, 3]
append() One object (the whole list) [1, 2, 3, [4, 5, 6]]
extend() Each item from the iterable [1, 2, 3, 4, 5, 6]

This difference applies to lists and to array.array objects. See Concatenate Lists in Python when you need to join sequences without mutation.

Performance comparison

Method Description Complexity Best use
list.append() One element at end O(1) Single items in a loop
list.extend() Many elements at once O(k) Iterable batches
list.insert() Insert at index O(n) Small lists
array.append() One typed element O(1) stdlib numeric buffers
numpy.append() New array with values O(n) Rare one-off joins
numpy.insert() New array with insert O(n) Rare indexed inserts
numpy.concatenate() Join along axis O(n) Repeated NumPy growth

For large NumPy workloads, avoid numpy.append() inside tight loops. Build a list of arrays and call numpy.concatenate() once, or pre-allocate the target array.

import timeit

# append() in a loop
start = timeit.default_timer()
lst = []
for i in range(10000):
    lst.append(i)
t_append = timeit.default_timer() - start

# extend() once
start = timeit.default_timer()
lst = []
lst.extend(range(10000))
t_extend = timeit.default_timer() - start

print(f"append loop: {t_append:.6f}s")
print(f"extend once: {t_extend:.6f}s")

extend() typically finishes faster than thousands of append() calls because Python grows the internal buffer in fewer steps.

Common errors and debugging

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

append() treats the iterable as a single object:

arr = [1, 2, 3]
arr.append([4, 5, 6])
print(arr)  # [1, 2, 3, [4, 5, 6]]

Use extend() to flatten the values in:

arr = [1, 2, 3]
arr.extend([4, 5, 6])
print(arr)  # [1, 2, 3, 4, 5, 6]

Type mismatch with NumPy arrays

NumPy arrays hold one dtype. Adding floats to an integer array upgrades the dtype:

import numpy as np

arr = np.array([1, 2, 3], dtype=int)
arr = np.append(arr, [4.5, 6.7])
print(arr)       # [1.  2.  3.  4.5 6.7]
print(arr.dtype) # float64

Pass matching types, or cast first:

import numpy as np

arr = np.array([1, 2, 3], dtype=int)
arr = np.append(arr, [4, 6])
print(arr)       # [1 2 3 4 6]
print(arr.dtype) # int64

Adding elements to a tuple

Tuples are immutable. append() raises AttributeError:

my_tuple = (1, 2, 3)
my_tuple.append(4)  # AttributeError

Convert to a list, add, and convert back if you need a tuple:

my_list = list((1, 2, 3))
my_list.append(4)
my_tuple = tuple(my_list)
print(my_tuple)  # (1, 2, 3, 4)

FAQs

1. How do I add an element to the end of an array in Python?

For a list, call append():

nums = [1, 2, 3]
nums.append(4)
print(nums)  # [1, 2, 3, 4]

For array.array, the call is the same:

import array

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

For NumPy, assign to a new variable because numpy.append() returns a copy:

import numpy as np

arr = np.array([1, 2, 3])
arr = np.append(arr, 4)
print(arr)  # [1 2 3 4]

2. What is the difference between append() and extend() in Python?

append() adds one object. extend() walks an iterable and adds each value. Passing a list to append() nests the list. Passing the same list to extend() flattens the values into the parent sequence.

3. How do I add an element at a specific index in Python?

Call insert(index, value) on a list or array.array:

nums = [10, 30, 40]
nums.insert(1, 20)
print(nums)  # [10, 20, 30, 40]

For NumPy, use numpy.insert() and store the returned array:

import numpy as np

arr = np.array([10, 30, 40])
arr = np.insert(arr, 1, 20)
print(arr)  # [10 20 30 40]

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

A list is a built-in sequence. An array.array holds one numeric type and uses less memory for large numeric buffers. A NumPy ndarray adds vectorized math and fixed dtype rules. Lists accept mixed types like strings and integers in the same sequence. Arrays and NumPy ndarrays do not.

5. How do I add elements to an array in a loop?

Call append() once per value, or extend() when each iteration produces a batch:

evens = []
for n in range(10):
    if n % 2 == 0:
        evens.append(n)
print(evens)  # [0, 2, 4, 6, 8]

For NumPy, collect arrays in a list and concatenate once instead of repeated numpy.append() calls.

Conclusion

You now know how to add to an array in Python across three structures: lists, the array module, and NumPy. You compared append(), extend(), and insert(), saw how axis arguments shape NumPy output, and reviewed frequent mistakes for new and experienced developers.

What’s next

Keep building with these Python tutorials:

Run data scripts on DigitalOcean App Platform or GPU-backed Droplets without managing hardware. For AI workloads, explore the DigitalOcean AI Platform.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Anish Singh Walia
Anish Singh Walia
Editor
Sr Technical Content Strategist and Team Lead
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Category:

Still looking for an answer?

Was this helpful?

Thank you! very helpful

- Jul

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

- Mohanish

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

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

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

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

Dark mode is coming soon.