w3resource

How to convert a 2D NumPy array to a nested Python list and print it?

NumPy: Interoperability Exercise-10 with Solution

Write a NumPy program to convert a 2D NumPy array to a nested Python list and print the list.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D NumPy array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Original 2D NumPy array:",array_2d)
print("Type:",type(array_2d))
# Convert the 2D NumPy array to a nested Python list
nested_list = array_2d.tolist()
print("\n2D NumPy array to a nested Python list:")
# Print the nested Python list
print(nested_list)
print("Type:",type(nested_list))

Output:

Original 2D NumPy array: [[1 2 3]
 [4 5 6]
 [7 8 9]]
Type: <class 'numpy.ndarray'>

2D NumPy array to a nested Python list:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Type: <class 'list'>

Explanation:

  • Import NumPy Library: Import the NumPy library to work with NumPy arrays.
  • Create 2D NumPy Array: Define a 2D NumPy array with elements organized in rows and columns.
  • Convert to Nested List: Use the tolist() method of the NumPy array to convert it into a nested Python list.
  • Print Nested List: Output the resulting nested Python list 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 nested Python list to a 2D NumPy array and print it?
Next: How to convert a Pandas series to a NumPy array and print 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://w3resource.com/python-exercises/numpy/convert-a-2d-numpy-array-to-a-nested-python-list-and-print.php