HOWTO · Python
How to Declare 3D Array in Python
There are 3 main methods that can be used to declare a 3D array in Python, the list comprehensions, the multiplication method, and the numpy package.
On this page
A three-dimensional structure in Python can be a nested list or a NumPy ndarray. Use nested list comprehensions for independent Python lists, list multiplication only when its shared references are acceptable, or NumPy for numerical array operations.
Declare 3D List Using List Comprehensions in Python
A nested list comprehension builds ordinary Python lists, with a new inner list created at each level. The list comprehension syntax below creates a zero-filled structure with shape 2 × 2 × 2: two outer items, each containing two rows of two values.
Run this example:
n = 2
distance = [[[0 for k in range(n)] for j in range(n)] for i in range(n)]
print(distance)
print((len(distance), len(distance[0]), len(distance[0][0])))
The three nested loops correspond to the three dimensions. Change n or use a different size for each range to build a non-cubic shape.
Declare 3D List Using Multiplication Method in Python
The * operator repeats a list, but it does not recursively copy the lists inside it. In the expression below, the repeated positions refer to the same inner lists. Updating one position can therefore change other positions that share that list:
n = 2
distance = [[[0] * n] * n] * n
distance[0][0][0] = 7
print(distance)
For independent nested lists, use a comprehension at each level, such as [[[0] * n for _ in range(n)] for _ in range(n)]. Multiplication is suitable for repeating immutable values or when shared references are intentional; it is not equivalent to the comprehension for mutable nested data.
Declare 3D Array Using the NumPy Package in Python
Use NumPy when you need an ndarray and numerical operations across its axes. It is an external package; install it in the Python environment used by your project with pip install numpy before running this example. The shape tuple gives the size of each axis, and np.zeros fills the array with zeros. Its default dtype is float.
try:
import numpy as np
except ImportError:
print("NumPy is not installed in this Python environment.")
else:
new_array = np.zeros((2, 2, 2))
print(new_array.shape)
print(new_array.dtype)
The displayed values of a NumPy array are formatted differently from a nested list, but both dimensions and zero initialization are set by the shape passed to np.zeros. For integer zeros, pass dtype=int, for example np.zeros((2, 2, 2), dtype=int). See the NumPy overview and np.zeros reference for details.