Skip to content

3D array Python

  • by

In Python, a 3D array is a data structure that can hold a collection of elements organized in a three-dimensional grid-like structure. It is an extension of a 2D array, where each element in the 3D array is identified by its indices in three dimensions: row, column, and depth.

A 3D array can be visualized as a stack of 2D arrays. It can be used to represent volumetric data or any data that requires three-dimensional indexing. Each element in the 3D array is accessed using three indices.

Here’s an example of a simple 3D array with dimensions 2x3x4:

[
  [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
  ],
  [
    [13, 14, 15, 16],
    [17, 18, 19, 20],
    [21, 22, 23, 24]
  ]
]

3D array Python example

In Python, you can create a 3D array using nested lists or by using libraries like NumPy. Here’s the syntax for creating a 3D array using both approaches:

Using nested lists:

# Create a 3D array using nested lists
array_3d = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

The above example, array_3d is a 3D array created using nested lists. It contains two 2D arrays, each with two rows and three columns.

Using NumPy arrays:

import numpy as np

# Create a 3D array using NumPy
array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

In the above example, array_3d is a 3D array created using the NumPy library. The np.array() function is used to convert the nested lists into a NumPy array.

Here’s an example of creating, accessing, and modifying a 3D array in Python using nested lists:

# Create a 3D array using nested lists
array_3d = [
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
    [[19, 20, 21], [22, 23, 24], [25, 26, 27]]
]

# Accessing elements in the 3D array
print(array_3d[1][2][0])  # Output: 16

# Modifying elements in the 3D array
array_3d[0][1][2] = 99
print(array_3d) 

Or using NumPy:

import numpy as np

# Create a 3D array using NumPy
array_3d = np.array([
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
    [[19, 20, 21], [22, 23, 24], [25, 26, 27]]
])

# Accessing elements in the 3D array
print(array_3d[1, 2, 0])  # Output: 16

# Modifying elements in the 3D array
array_3d[0, 1, 2] = 99
print(array_3d) 

Output:

3D array Python

Comment if you have any doubts or suggestions on this Python Array topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading