w3resource

How to convert a list of lists of lists to a 3D NumPy array and print it?


Write a NumPy program to convert a list of lists of lists to a 3D NumPy array and print the array.

Sample Solution:

Python Code:

import numpy as np

# Define a nested list of lists of lists
list_of_lists = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

print("Original nested list of lists of lists:",list_of_lists)
print(type(list_of_lists))

# Convert the nested list to a 3D NumPy array
print("\nNested list to a 3D NumPy array:")
array_3d = np.array(list_of_lists)

# Print the 3D NumPy array
print(array_3d)
print(type(array_3d))

Output:

Original nested list of lists of lists: [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
<class 'list'>

Nested list to a 3D NumPy array:
[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]
<class 'numpy.ndarray'>

Explanation:

  • Import NumPy Library: Import the NumPy library to work with arrays.
  • Define Nested List: Create a nested list of lists of lists with some example data.
  • Convert to 3D NumPy Array: Use the np.array() function to convert the nested list into a 3D NumPy array.
  • Print 3D NumPy Array: Output the resulting 3D NumPy array to verify the conversion.

Python-Numpy Code Editor: