w3resource

Convert Python list to NumPy array and print

NumPy: Interoperability Exercise-1 with Solution

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

Sample Solution:

Python Code:

import numpy as np

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

Output:

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

Explanation:

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

Python-Numpy Code Editor:

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

Previous:NumPy Interoperability Exercise Home.
Next: Convert NumPy array to Python list 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://198.211.115.131/python-exercises/numpy/convert-python-list-to-numpy-array-and-print.php