w3resource

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


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: