Python | Creating a 3D list

Python Methods and Functions

A three-dimensional list means that we need to compose a list with three parameters, i.e. (axbxc), just like a three-dimensional array in other languages. In this program, we will try to generate a 3D list with the content "#". Let's look at the following examples:

 Input: 3 x 3 x 3 Output: [[['#', '#', '#'], ['#', '#', '#' ], ['#', '#', '#']], [['#', '#', '#'], ['#', '#', '#'], ['#' , '#', '#']], [['#', '#', '#'], ['#', '#', '#'], ['#', '#', ' # ']]] Input: 5 x 3 x 2 Output: [[[' # ',' # ',' # ',' # ',' # '], [' # ',' # ',' # ' , '#', '#'], ['#', '#', '#', '#', '#']], [['#', '#', '#', '#' , '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#']] ] 

# Python program for printing a 3D list
# importing pretty printed

import pprint

 

def ThreeD (a, b, c):

lst = [[[ '#' for col in range (a)] for col in range (b)] for row in range (c)]

return lst

 
Driver code

col1 = 5

col2 = 3

row = 2

# used a nice typing function
pprint.pprint (ThreeD (col1, col2, row))

Output:

 [[['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#']], [['#', '#', '#', '#', '#'], ['#', '#', '#', '#', '#'], ['#', '#', '#, ',' # ']]] 

Refer to a complete understanding of this topic.

Now let's assume that we need to merge the two 3D lists into one.

# Python program to combine two 3D lists into one
# import pretty print

import pprint

 

def ThreeD (a, b , c):

lst1 = [[[ '1' for col in range (a)] for col in range (b)] for row in range (c)]

  lst2 = [[[[ '2' for col in range (a)] for col in range (b)] for row in range (c)]

# Combine using the & quot; + & quot; operator

lst = lst1 + lst2

return lst

 
Driver code

col1 = 3

col2 = 3

row = 3

 
# used a nice print function
pprint.pprint (ThreeD ( col1, col2, row))

Output:

 [[['1',' 1', '1'], [' 1', '1',' 1'], ['1',' 1', '1']], [ ['1',' 1', '1'], [' 1', '1',' 1'], ['1',' 1', '1']], [[' 1', ' 1', '1'], [' 1', '1',' 1'], ['1',' 1', '1']], [[' 2', '2',' 2' ], ['2',' 2', '2'], [' 2', '2',' 2']], [['2',' 2', '2'], [' 2' , '2',' 2'], ['2',' 2', '2']], [[' 2', '2',' 2'], ['2',' 2', ' 2'], ['2',' 2', '2 ']]] 




Tutorials