w3resource

Convert Python tuple to NumPy array and print


3. Tuple to Array Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a tuple of tuples into a multidimensional NumPy array and enforce a uniform shape.
  • Write a Numpy program to convert a Python tuple containing mixed numeric and boolean values into a NumPy array with a specific dtype.
  • Write a Numpy program to convert a tuple containing a combination of lists and tuples to a NumPy array, handling potential type conflicts.
  • Write a Numpy program to convert a tuple of varying-length sequences into a NumPy array using object dtype and then convert it to a homogeneous numeric array.

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.



Follow us on Facebook and Twitter for latest update.