There are the following methods to convert a tuple into an array in Python.
- Method 1: Using the numpy.asarray() function
- Method 2: Usign the numpy.array() function
Method 1: Using the numpy.asarray()
To convert a tuple to an array in Python, you can use the numpy.asarray() function. For example, numpy.asarray((11, 21, 19)) returns [11 21 19].
Example
import numpy as np
tup = (11, 21, 19, 18, 46, 29)
print(tup)
print(type(tup))
print("After converting Python tuple to array")
arr = np.asarray(tup)
print(arr)
print(type(arr))
Output
(11, 21, 19, 18, 46, 29)
<class 'tuple'>
After converting Python tuple to array
[11 21 19 18 46 29]
<class 'numpy.ndarray'>
In this example, we imported the numpy module.
We then defined a tuple using the tuple() function.
For example, check the data type, you can use the type() function.
We got the array in return by using the np.asarray() function and passing a tuple as an argument.
If we check the data type of return value, it is a numpy array, which we wanted.
Converting a tuple of lists into an array
To convert a tuple of lists into an array, you can use the np.asarray() function and then flatten the array using the flatten() method to convert it into a one-dimensional array.
import numpy as np
tup = ([11, 21, 19], [18, 46, 29])
print("After converting Python tuple of lists to array")
arr = np.asarray(tup)
print(arr)
fla_arr = arr.flatten()
print(fla_arr)
Output
After converting Python tuple of lists to array
[[11 21 19]
[18 46 29]]
[11 21 19 18 46 29]
The numpy.asarray() converts a tuple of lists to an array. Still, it will create a two-dimensional array, and to convert it into a one-dimensional array, use the array.flatten() method.
Method 2: Using np.array()
The numpy.array() method takes a Python object as an argument and returns an array. We will pass a tuple object to the np.array() function, converting that tuple to an array.
import numpy as np
tup = ([11, 21, 19], [18, 46, 29])
print("After converting Python tuple to array using np.array()")
arr = np.array(tup)
print(arr)
print("After flattening the array")
fla_arr = arr.flatten()
print(fla_arr)
Output
After converting Python tuple to array using np.array()
[[11 21 19]
[18 46 29]]
After flattening the array
[11 21 19 18 46 29]
The np.array() function works almost the same as the np.asarray() and returns the converted array.
Assuming Python list as an array
If you don’t want to use a numpy array and make a list as an array, use the list comprehension to convert a tuple to an array.
lt = []
tup1 = (11, 19, 21)
tup2 = (46, 18, 29)
lt.append(tup1)
lt.append(tup2)
arr = [x for xs in lt for x in xs]
print(arr)
Output
[11, 19, 21, 46, 18, 29]
That is it for this tutorial.