w3resource

Convert NumPy array to Python tuple and Print


4. Array to Tuple Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a multidimensional NumPy array into a nested Python tuple while preserving the structure.
  • Write a Numpy program to convert a structured NumPy array into a tuple of tuples, ensuring each inner tuple represents a row.
  • Write a Numpy program to convert a NumPy array with custom dtypes into a tuple and verify that element types match the original array.
  • Write a Numpy program to convert a transposed NumPy array into a tuple and then reverse the operation to regain the original array.

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.



Follow us on Facebook and Twitter for latest update.