惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
G
Google Developers Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
S
SegmentFault 最新的问题
宝玉的分享
宝玉的分享
博客园 - Franky
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
月光博客
月光博客
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
Microsoft Security Blog
Microsoft Security Blog
Last Week in AI
Last Week in AI
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
J
Java Code Geeks
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志

DigitalOcean Community Tutorials

It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu
Python Array Add: How to Append, Extend & Insert Elements
Pankaj Kumar · 2026-06-12 · via DigitalOcean Community Tutorials

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.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.