w3resource

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


10. 2D Array to Nested List Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a 2D NumPy array into a nested Python list and then flatten it back into a 1D list using recursion.
  • Write a Numpy program to convert a 2D array to a nested list and then filter rows based on a condition applied to list elements.
  • Write a Numpy program to convert a transposed 2D NumPy array to a nested list and then reassemble the original array structure.
  • Write a Numpy program to convert a 2D NumPy array with mixed numeric types into a nested list and then cast all elements to float.

Go to:


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?

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.