w3resource

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

NumPy: Interoperability Exercise-9 with Solution

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:

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

Previous: How to convert a NumPy array to a Dictionary with Indices as keys?.
Next: How to convert a 2D NumPy array to a nested Python list 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-nested-python-list-to-a-2d-numpy-array-and-print.php