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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics