Convert NumPy array to Python tuple and Print
NumPy: Interoperability Exercise-4 with Solution
Write a NumPy program to convert a NumPy array to a Python tuple and print the tuple.
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 tuple
python_tuple = tuple(numpy_array)
print("\nNumPy array to a Python tuple:")
# Print the Python tuple
print(python_tuple)
print("Type:",type(python_tuple))
Output:
Original NumPy array: [1 2 3 4 5] Type: <class 'numpy.ndarray'> NumPy array to a Python tuple: (1, 2, 3, 4, 5) Type: <class 'tuple'>
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 tuple: The NumPy array is converted to a Python tuple using the tuple() function.
- Printing the tuple: The resulting Python tuple is printed.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous:Convert Python tuple to NumPy array and print.
Next: Convert Pandas DataFrame to NumPy array and print.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-tuple-and-print.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics