Here are three ways to convert a tuple into an array in Python:
- Using numpy.array()
- Using numpy.asarray()
- Using array Module
Method 1: Using numpy.array()
The numpy.array() method takes an object as an argument and returns an Nympy array.
Visual Representation
Example 1: Basic Usage
# Importing the numpy package
import numpy as np
# Defining a tuple
tup = (11, 21, 19, 18, 46, 29)
print(tup) # Printing the original tuple
print(type(tup)) # Printing the type of the tuple to confirm it's a tuple
# Converting the tuple to a numpy array
arr = np.array(tup)
print(arr) # Printing the newly created numpy array
print(type(arr)) # Printing the type of arr to confirm it's now a numpy array
Output
(11, 21, 19, 18, 46, 29)
<class 'tuple'>
[11 21 19 18 46 29]
<class 'numpy.ndarray'>
Method 2: Using numpy.asarray()
Visual Representation
Example 1: Basic Usage
# Importing the numpy package
import numpy as np
# Defining a tuple
tup = (11, 21, 19, 18, 46, 29)
print(tup) # Printing the original tuple
print(type(tup)) # Printing the type of the tuple to confirm it's a tuple
# Converting the tuple to a numpy array
arr = np.asarray(tup)
print(arr) # Printing the newly created numpy array
print(type(arr)) # Printing the type of arr to confirm it's now a numpy array
Output
(11, 21, 19, 18, 46, 29)
<class 'tuple'>
After converting tuple to array
[11 21 19 18 46 29]
<class 'numpy.ndarray'>
Example 2: Flattening a List of Tuples into a Single Dimensional Array
import numpy as np
# Defining a tuple of lists
tup = ([11, 21, 19], [18, 46, 29])
# Converting the tuple of lists to a numpy array
arr = np.asarray(tup)
# Printing the numpy array
print(arr)
print(type(arr))
# Flattening the numpy array into a single-dimensional array
flat_arr = arr.flatten()
# Printing the flattened array
print(flat_arr)
Output
[[11 21 19]
[18 46 29]]
<class 'numpy.ndarray'>
[11 21 19 18 46 29]
Method 3: Using array Module
This method provides a lightweight implementation of arrays with specific data types and basic functionalities.
import array
tup = (11, 21, 19, 18, 46, 29)
arr = array.array('i', tup) # 'i' is the type code for integers
print(arr)
print(type(arr))
Output
array('i', [11, 21, 19, 18, 46, 29])
<class 'array.array'>