Array to Tuple in Python

  1. Array to Tuple With the tuple() Function in Python
  2. Array to Tuple With the map() Function in Python

This tutorial will introduce the methods to a NumPy array to tuples in Python.

Array to Tuple With the tuple() Function in Python

If we have an array that consists of tuples and want to convert it into 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. The following code example shows us how to convert a NumPy array to a tuple with Python’s tuple() function.

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))

In the above code, we converted the NumPy array array to the tuple result with Python’s tuple() function. We first created an array containing tuples as its elements with the np.array() function and displayed the array elements. We then converted all the elements of the array to the tuple result with the tuple() function and displayed the elements of the result tuple.

Array to Tuple With the map() Function in Python

The map() function is used to apply a particular method to all the elements of an iterable in Python. The map() function 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. The following code example shows us how we can convert a NumPy array to a tuple with the map() function in Python.

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 the NumPy array array to the tuple result with the map() function in Python. We first created an array containing tuples as its elements with the np.array() function and displayed the array elements. We then 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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Arrays

  • Get Column of Numpy Array