w3resource

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

NumPy: Interoperability Exercise-17 with Solution

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:

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

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?

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://198.211.115.131/python-exercises/numpy/convert-a-list-of-lists-of-lists-to-a-3d-numpy-array-and-print.php