w3resource

Convert NumPy array to Python list and print


NumPy: Interoperability Exercise-2 with Solution


Write a NumPy program to convert a NumPy array to a native Python list and print the list.

Sample Solution:

Python Code:

import numpy as np

# Initialize a NumPy array
numpy_array = np.array([1, 2, 3, 4, 5])
print("Original NumPy array:",numpy_array)
print("Type:",type(numpy_array))
# Convert the NumPy array to a Python list
python_list = numpy_array.tolist()
print("\nNumPy array to a Python list:")
# Print the Python list
print(python_list)
print("Type:",type(python_list))

Output:

Original NumPy array: [1 2 3 4 5]
Type: <class 'numpy.ndarray'>

NumPy array to a Python list:
[1, 2, 3, 4, 5]
Type: <class 'list'>

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing a NumPy array: A NumPy array is initialized with some elements.
  • Converting to Python list: The NumPy array is converted to a Python list using the tolist() method.
  • Printing the list: The resulting Python list is printed.

Python-Numpy Code Editor: