Python

How to Create a Two-Dimensional Array in Python

Python · · Published 2026-10-24

Rows of brown eggs sitting in a cardboard egg tray
Brown eggs lined up in rows and columns in a cardboard tray.

In plain Python, create a two-dimensional array as a list of lists with a comprehension: grid = [[0] * cols for _ in range(rows)]. For numeric work, use NumPy: np.zeros((rows, cols)). Never write [[0] * cols] * rows, which makes every row the same object.

Python has no built-in 2D array type. You either nest lists, which is flexible and dependency-free, or use a NumPy ndarray, which is compact, fast and supports real matrix operations. The examples below were run on Python 3.13 and NumPy 2.5.

Nested lists with a list comprehension

rows, cols = 3, 4
grid = [[0] * cols for _ in range(rows)]
grid[1][2] = 7
print(grid)
print(len(grid), len(grid[0]))
[[0, 0, 0, 0], [0, 0, 7, 0], [0, 0, 0, 0]]
3 4

The comprehension runs [0] * cols once per row, so each row is a new, independent list. len(grid) gives the number of rows and len(grid[0]) the number of columns. Lists of lists can also be jagged (rows of different lengths), which a NumPy array cannot.

You can initialise from a function of the indices just as easily:

table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

The [[0] * n] * m aliasing pitfall

This looks equivalent but is not:

bad = [[0] * 4] * 3
bad[1][2] = 7
print(bad)
print(bad[0] is bad[1] is bad[2])

good = [[0] * 4 for _ in range(3)]
print(good[0] is good[1])
[[0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0]]
True
False

Multiplying a list repeats references to its elements. The inner [0] * 4 is fine because integers are immutable, but the outer * 3 produces three references to one list, so writing into "row 1" changes all of them. The same trap applies to [[]] * n and to dict.fromkeys(keys, []). The Python FAQ covers it under "How do I create a multidimensional list?".

Indexing and iterating

matrix = [
    [1, 2, 3],
    [4, 5, 6],
]
print(matrix[1][2])      # row 1, column 2
print(matrix[-1][0])     # last row, first column
print([row[1] for row in matrix])   # column 1

for i, row in enumerate(matrix):
    for j, value in enumerate(row):
        print(f"({i},{j})={value}", end=" ")
print()

total = sum(sum(row) for row in matrix)
print(total)
6
4
[2, 5]
(0,0)=1 (0,1)=2 (0,2)=3 (1,0)=4 (1,1)=5 (1,2)=6
21

Indexing is always matrix[row][col]: the first subscript returns a row list, the second indexes into it. Extracting a column requires a comprehension, because list slicing works only along the outer dimension (matrix[0:1] returns rows, not columns).

Transposing, flattening and copying

matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [list(col) for col in zip(*matrix)]
print(transposed)

flat = [x for row in matrix for x in row]
print(flat)

import copy
shallow = matrix.copy()
deep = copy.deepcopy(matrix)
matrix[0][0] = 99
print(shallow[0][0], deep[0][0])
[[1, 4], [2, 5], [3, 6]]
[1, 2, 3, 4, 5, 6]
99 1

zip(*matrix) unpacks the rows as separate arguments, and zip groups the first elements, then the second, and so on, which is exactly a transpose. It yields tuples, hence list(col). If rows have different lengths, zip silently truncates to the shortest; pass strict=True (Python 3.10+) to raise instead.

Copying is the second aliasing trap: matrix.copy(), matrix[:] and list(matrix) copy only the outer list, so the rows are still shared. Use copy.deepcopy(matrix) or [row[:] for row in matrix] for an independent copy.

NumPy arrays

For numerical data, a NumPy ndarray stores values in one contiguous, typed block of memory and supports vectorised operations, real 2D slicing and linear algebra.

import numpy as np

a = np.zeros((3, 4), dtype=int)
a[1, 2] = 7
print(a)
print(a.shape, a.dtype, a.ndim)

b = np.arange(1, 7).reshape(2, 3)
print(b)
print(b[:, 1])          # column 1
print(b[0, 1:])         # row 0, columns 1..end
print(b.T)              # transpose
print(b * 10 + 1)       # vectorised arithmetic
print(b.sum(axis=0), b.sum(axis=1))
[[0 0 0 0]
 [0 0 7 0]
 [0 0 0 0]]
(3, 4) int64 2
[[1 2 3]
 [4 5 6]]
[2 5]
[2 3]
[[1 4]
 [2 5]
 [3 6]]
[[11 21 31]
 [41 51 61]]
[5 7 9] [ 6 15]

Key points:

The NumPy absolute beginner's guide covers creation and indexing in more depth.

Two NumPy surprises

import numpy as np

b = np.arange(1, 7).reshape(2, 3)
view = b[:, :2]
view[0, 0] = 100
print(b[0, 0])

a = np.zeros((2, 2), dtype=int)
a[0, 0] = 3.9
print(a[0, 0])
100
3

Basic slices are views of the same memory, so modifying a slice modifies the original; call .copy() when you need independence. And because the dtype is fixed, assigning 3.9 to an integer array silently truncates it to 3.

Why not the array module?

The standard library's array module provides compact, typed one-dimensional sequences only:

from array import array

row = array("i", [1, 2, 3])
print(row, row.itemsize)
try:
    array("i", [[1, 2], [3, 4]])
except TypeError as e:
    print("TypeError:", e)

grid = [array("i", [0] * 3) for _ in range(2)]
grid[1][0] = 5
print(grid)
array('i', [1, 2, 3]) 4
TypeError: 'list' object cannot be interpreted as an integer
[array('i', [0, 0, 0]), array('i', [5, 0, 0])]

You can build a list of array rows to save memory, but you get none of NumPy's 2D indexing or arithmetic. In practice it is rarely the right tool for a matrix.

Which one should you use?

NeedUse
Small grid, game board, mixed types, no dependenciesList of lists
Rows of different lengthsList of lists
Numeric data, maths, large sizesNumPy ndarray
Column slicing, transposes, matrix multiply (@)NumPy ndarray
Labelled rows and columns, mixed column typespandas DataFrame
Memory-compact 1D typed sequencearray.array

A list of lists stores a pointer per element to a separate Python object, so a 1000 × 1000 grid of floats costs many times the 8 MB a float64 NumPy array uses, and every loop over it runs in the interpreter.

Common pitfalls

Summary

Use [[value] * cols for _ in range(rows)] for a list-of-lists 2D array, index it as grid[r][c], transpose with zip(*grid) and copy rows with deepcopy. Switch to np.zeros((rows, cols), dtype=...) when you need speed, column slices or arithmetic, keeping in mind that NumPy slices are views and dtypes are fixed. Avoid [[0] * n] * m entirely.