w3resource

Python: Generate a 3D array

Python List: Exercise - 13 with Solution

Generate 3D Array

Write a Python program to generate a 3*4*6 3D array whose each element is *.

Visual Presentation:

Python List: Generate a 3D array

Sample Solution:

Python Code:

# Create a 3D array using list comprehensions, with 3 rows, 4 columns, and each element initialized as '*'
array = [[['*' for col in range(6)] for col in range(4)] for row in range(3)]

# Print the resulting 3D array
print(array)

Sample Output:

[[['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '
*', '*', '*', '*']], [['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*'
, '*'], ['*', '*', '*', '*', '*', '*']], [['*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*'], ['*'
, '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*']]]

Explanation:

array = [[ ['*' for col in range(6)] for col in range(4)] for row in range(3)]

In the above code -

  • The outermost range(3) loop creates 3 outermost lists, which represent the first dimension of the 3D array.
  • The second range(4) loop creates 4 sub-lists for each outermost list, representing the second dimension.
  • The innermost range(6) loop creates 6 innermost lists for each sub-list, representing the third dimension.
  • The ' * ' character is assigned to every element of the innermost list using the list comprehension.

So, the resulting array is a 3D array of size 3x4x6, with every element initialized to the character '*'.

Finally print() function prints the said array.

Flowchart:

Flowchart: Generate a 3D array

Python Code Editor:

Previous: Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
Next: Write a Python program to print the numbers of a specified list after removing even numbers from it.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-13.php