w3resource

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


16. 3D Array to Nested List Conversion

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

Sample Solution:

Python Code:

import numpy as np

# Create a 3D NumPy array
array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print("Original 3D NumPy array:",array_3d)
print(type(array_3d))
# Convert the 3D NumPy array to a nested list of lists of lists
list_of_lists = array_3d.tolist()

# Print the list of lists of lists
print("\nlist of lists of lists:")
print(list_of_lists)
print(type(list_of_lists))

Output:

Original 3D NumPy array: [[[ 1  2  3]
  [ 4  5  6]]

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

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

Explanation:

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

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a 3D NumPy array into a nested list of lists of lists and then recursively compute the depth of the nested list.
  • Write a Numpy program to convert a 3D array to a nested list and then flatten it back while preserving the original 3D shape.
  • Write a Numpy program to convert a 3D NumPy array to a nested list and then apply a custom function to each innermost list.
  • Write a Numpy program to convert a 3D array into a nested list and then validate element ordering by comparing with the array’s ravelled version.

Go to:


Previous: How to read a CSV file into a NumPy array and print it?
Next: How to convert a list of lists of lists to a 3D NumPy array and print it?

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.