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:

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

Previous:Convert Python list to NumPy array and print.
Next: Convert Python tuple to NumPy array and print.

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://www.w3resource.com/python-exercises/numpy/convert-numpy-array-to-python-list-and-print.php