
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to create 3D list.
In Python, A 3D list is also called a three-dimensional array (list of lists of lists). It can be visualized as a cube or a set of tables stacked together. It is commonly used to represent data with three indices. For example, a matrix of images (height, width, depth).
In this article, we are going to learn how to create a 3D list. As Python does not have built-in support for multi-dimensional arrays like other programming languages, but using the nested lists and loops, we can create and manipulate 3D lists.
Creating a 3D List
In the following example, we are going to create a 3D list with the sequential numbers starting from 1.
a, b, c = 2, 2, 3 x = 1 y = [] for i in range(a): z = [] for j in range(b): row = [] for k in range(c): row.append(x) x += 1 z.append(row) y.append(z) print("Result :") print(y)
The output of the above program is as follows -
Result : [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
Creating 3D List using Python List Comprehension
The Python list comprehension offers a simple way to create a list using a single line of code. It combines loops and conditional statements, making it efficient compared to the traditional methods of list construction.
Syntax
Following is the syntax of Python list comprehension -
newlist = [expression for item in iterable if condition == True]
In this scenario, we are going to use list comprehension to generate the 3D list.
Example
Let's look at the following example, where we are going to construct a 3D list of size 2*3*4 filled with zeros.
x = 2 y = 3 z = 4 result = [[[0 for _ in range(z)] for _ in range(y)] for _ in range(x)] print("Result :") print(result)
The output of the above program is as follows -
Result : [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]