How to Convert NumPy Array to Tuple

Muhammad Maisam Abbas Feb 02, 2024
  1. Convert NumPy Array to Tuple With the tuple() Function in Python
  2. Convert NumPy Array to Tuple With the map() Function in Python
How to Convert NumPy Array to Tuple

This tutorial will introduce how to convert a NumPy array to a tuple in Python.

Convert NumPy Array to Tuple With the tuple() Function in Python

If we need to convert a numpy array to tuples, we can use the tuple() function in Python. The tuple() function takes an iterable as an argument and returns a tuple consisting of the elements of the iterable.

import numpy as np

array = np.array(((0, 1), (2, 3)))
print(array)

result = tuple([tuple(e) for e in array])
print(result)

Output:

[[0 1]
 [2 3]]
((0, 1), (2, 3))

We first created an array containing tuples as its elements with the np.array() function and printed the array elements. We then converted all the elements of the array to the tuple result with the tuple() function and printed the elements of the result tuple.

Convert NumPy Array to Tuple With the map() Function in Python

The map() function applies a particular function to all the iterable elements in Python. It takes the function to be applied and the iterable as arguments and returns an iterator where the function is applied to each element of the iterable object. We can use the map() function to apply the tuple() function on each element of our NumPy array and then apply the tuple() function to the results to convert them to a single tuple.

import numpy as np

array = np.array(((0, 1), (2, 3)))
print(array)

result = tuple(map(tuple, array))
print(result)

Output:

[[0 1]
 [2 3]]
((0, 1), (2, 3))

In the above code, we converted all the elements of the array to tuples with the map(tuple, array) function and then stored all the tuples inside one single tuple result with another tuple() function. In the end, we printed the elements of the result tuple.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn