w3resource

Convert Python tuple to NumPy array and print


NumPy: Interoperability Exercise-3 with Solution


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

Sample Solution:

Python Code:

import numpy as np

# Initialize a Python tuple
python_tuple = (1, 2, 3, 4, 5)
print("Original Python tuple:",python_tuple)
print("Type:",type(python_tuple))
# Convert the Python tuple to a NumPy array
numpy_array = np.array(python_tuple)
print("\nPython tuple to a NumPy array:")
# Print the NumPy array
print(numpy_array)
print("Type:",type(numpy_array))

Output:

Original Python tuple: (1, 2, 3, 4, 5)
Type: <class 'tuple'>

Python tuple 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 tuple: A Python tuple is initialized with some elements.
  • Converting to NumPy array: The Python tuple is converted to a NumPy array using np.array().
  • Printing the array: The resulting NumPy array is printed.

Python-Numpy Code Editor: