w3resource

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


9. Nested List to 2D Array Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a nested Python list with inconsistent inner list lengths into a 2D NumPy array using padding.
  • Write a Numpy program to convert a nested list of strings representing numbers into a 2D numeric NumPy array with proper conversion.
  • Write a Numpy program to convert a nested Python list into a 2D NumPy array and then perform a dynamic reshape based on user input.
  • Write a Numpy program to convert a nested list into a 2D NumPy array and validate the conversion by comparing row sums.

Go to:


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?

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.