Python
arrays
programming
coding tutorial
data structures

How to declare and add items to an array in Python

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Python, most developers use lists when they say array, but Python also provides array.array and NumPy arrays for typed numeric workloads. Choosing the right structure depends on performance, memory, and API needs. This guide explains how to declare each structure and add items safely.

Use Lists For General Purpose Collections

Lists are dynamic, allow mixed types, and support many insertion methods.

python
1items = []
2items.append("apple")
3items.append("banana")
4items.extend(["orange", "grape"])
5items.insert(1, "kiwi")
6
7print(items)

Key operations:

  • append(x) adds one item to end.
  • extend(iterable) adds many items.
  • insert(i, x) adds at a position.

Lists are ideal for application level data where flexibility matters more than strict type control.

Typed Arrays With array.array

If you need compact storage for many numbers of one type, use the built in array module.

python
1from array import array
2
3nums = array('i', [1, 2, 3])
4nums.append(4)
5nums.extend([5, 6, 7])
6
7print(nums)
8print(nums.typecode)

Type codes enforce element type, for example 'i' for signed integers or 'f' for floats. Attempting to append an incompatible type raises an error.

NumPy Arrays For Numerical Computing

For data science or numeric heavy workloads, NumPy arrays are usually the best choice.

python
1import numpy as np
2
3arr = np.array([1, 2, 3], dtype=np.int64)
4arr = np.append(arr, [4, 5])
5
6print(arr)
7print(arr.dtype)

Note that np.append returns a new array. It does not modify in place. For frequent growth operations, collect values in a Python list first, then convert once to NumPy.

Choosing The Right Structure

Use this practical rule:

  • List for flexible general objects.
  • array.array for memory efficient typed simple numbers.
  • NumPy for vectorized numerical operations and matrix style workflows.

Do not force typed arrays where plain lists are simpler and more readable.

Adding Multiple Items Efficiently

Repeated concatenation with + can be slower for large loops because it creates new lists each time. Prefer append inside loops and extend for batches.

python
1values = []
2for i in range(5):
3    values.append(i * 10)
4
5more = [100, 110]
6values.extend(more)
7print(values)

This avoids unnecessary temporary objects.

Nested Arrays And Initialization

For nested structures, avoid multiplying mutable lists directly because inner rows may reference the same object.

python
1# bad for independent rows
2bad = [[0] * 3] * 2
3bad[0][0] = 9
4print(bad)
5
6# good
7good = [[0 for _ in range(3)] for _ in range(2)]
8good[0][0] = 9
9print(good)

This is a frequent bug in beginner and intermediate Python code.

Conversion Between Structures

You can convert between list and typed arrays when needed.

python
1from array import array
2
3lst = [1, 2, 3]
4arr = array('i', lst)
5back_to_list = list(arr)
6print(back_to_list)

For NumPy conversion:

python
1import numpy as np
2
3lst = [1, 2, 3]
4np_arr = np.array(lst)
5print(np_arr.tolist())

Conversion is useful at boundaries between libraries.

Practical API Design Tips

If your function accepts a sequence input, prefer type hints such as Sequence or Iterable instead of forcing callers to pass a list. This keeps your API flexible and lets users provide generators when appropriate.

When your function needs mutation operations like append, convert once internally and document that conversion behavior. Clear contracts make performance expectations explicit.

For team codebases, adopt a convention for when NumPy arrays are required versus optional. This avoids repeated conversions and inconsistent interfaces across modules.

Common Pitfalls

  • Calling Python lists arrays and expecting typed behavior.
  • Using np.append in tight loops and creating many copies.
  • Forgetting that array.array enforces one data type.
  • Creating nested lists with shared row references.
  • Choosing complex structures when a plain list is sufficient.

Summary

  • Python lists are the default dynamic array like structure.
  • array.array gives typed, compact storage for simple numeric values.
  • NumPy arrays are best for numerical and vectorized workflows.
  • Prefer append and extend for efficient growth patterns.
  • Understand structure semantics before optimizing for performance.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.