w3resource

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


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

Sample Solution:

Python Code:

import numpy as np

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

Output:

Original nested Python list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Type: <class 'list'>

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

Explanation:

  • Import NumPy Library: Import the NumPy library to utilize its array creation and manipulation functions.
  • Define Nested List: Create a nested Python list where each sublist represents a row of the 2D array.
  • Convert to 2D NumPy Array: Use np.array() to convert the nested list into a 2D NumPy array.
  • Print 2D Array: Output the resulting 2D NumPy array to verify the conversion.

Python-Numpy Code Editor: