w3resource

NumPy: Convert a NumPy array into Python list structure


Convert NumPy Array to Python List

Write a NumPy program to convert a NumPy array into a Python list structure.

Pictorial Presentation:

Python NumPy: Convert a NumPy array into Python list structure

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a 1-dimensional array 'x' with values from 0 to 5 and reshaping it into a 3x2 array
x = np.arange(6).reshape(3, 2)

# Printing a message indicating the original array elements will be shown
print("Original array elements:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating that the array will be converted to a Python list
print("Array to list:")

# Converting the NumPy array 'x' into a Python list using the tolist() method
print(x.tolist())

Sample Output:

Original array elements:                                                               
[[0 1]                                                                                 
 [2 3]                                                                                 
 [4 5]]                                                                                
Array to list:                                                                         
[[0, 1], [2, 3], [4, 5]]

Explanation:

In the above code –

‘x = np.arange(6).reshape(3, 2)’ creates a NumPy array x using np.arange(6), which generates an array with values from 0 to 5. Then, reshape the array into a 3x2 matrix using the reshape method.

print(x.tolist()): Convert the NumPy array ‘x’ to a nested list using the tolist method and print the resulting list.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to convert a multi-dimensional array into a nested Python list using the tolist() method.
  • Create a function that accepts an array and returns its Python list representation, then validates each element.
  • Test conversion of both 1D and 2D arrays to lists and check the types of the resulting elements.
  • Use recursive techniques to convert a structured array into a nested list and verify its structure.

Go to:


PREV : Generate 2D Gaussian-Like Array
NEXT : Access Array by Column


Python-Numpy Code Editor:

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.