w3resource

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


17. Nested List to 3D Array Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a deeply nested list of lists of lists into a 3D NumPy array and handle irregular inner list lengths.
  • Write a Numpy program to convert a nested list representing a 3D structure into a NumPy array and verify dimensions via shape attributes.
  • Write a Numpy program to transform a nested list to a 3D NumPy array and then perform slicing operations along each dimension.
  • Write a Numpy program to convert a nested list to a 3D array and then transpose the dimensions to test the array's consistency.

Go to:


Previous: How to convert a 3D NumPy array to a list of lists of lists?
Next: How to convert a Pandas DataFrame with mixed data types to a NumPy array?

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.