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: