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:

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

Previous:Convert NumPy array to Python list and print.
Next: Convert NumPy array to Python tuple 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://w3resource.com/python-exercises/numpy/convert-python-tuple-to-numpy-array-and-print.php