Open In App

Python - Creating a 3D List

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, 3D list represents a three dimensional data structure where we can organize elements in three axes (rows, columns, and depth). Let’s explore various ways to create a 3D list in Python.

Using Nested List Comprehensions

Nested list comprehensions are a concise way to create 3D lists by iterating over ranges for each dimension.

Python
# Create a 3D list with dimensions 2x3x4, initialized to 0
a = [[[0 for k in range(4)] for j in range(3)] for i in range(2)]
print(a)

Output
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

Explanation:

  • The innermost loop creates a list of size 4 initialized to 0.
  • The middle loop replicates this list 3 times to form a 2D list (rows × columns).
  • The outermost loop replicates the 2D list 2 times to form the 3D structure.

Let's see some more methods and see how we can create a 3D list in Python.

Table of Content

Using Loops

Using explicit nested loops, we can initialize a 3D list step by step. This method provides more control and is easier to debug.

Python
# Dimensions
x, y, z = 2, 3, 4

# Create 3D list
a = []
for i in range(x):
    temp = []
    for j in range(y):
        temp.append([0] * z)
    a.append(temp)

print(a)

Output
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

Explanation:

  • We first create a 2D list for each i iteration (outermost loop).
  • The inner loop appends rows to this 2D list.

Using NumPy

For numerical computations, using NumPy is more efficient and convenient.

Python
import numpy as np

# Create a 3D array with dimensions 2x3x4, initialized to 0
a = np.zeros((2, 3, 4))
print(a)

Explanation:

  • The np.zeros() function creates an array filled with 0 with the specified dimensions.
  • NumPy is optimized for large scale computations and is faster compared to native Python lists.

Next Article
Article Tags :
Practice Tags :

Similar Reads