Here are the 5 ways to convert a tuple to a list in Python:
- Using the list() function
- Using the list comprehension
- Using a for loop
- Using an asterisk(*) operator
- Using the map() Function
Method 1: Using the list() function
The list() function is a built-in function that takes an iterable, such as a tuple, as an argument and returns a list.
Visual Representation
Example
# Define a tuple with integers
number_tuple = (5, 10, 15, 20, 25)
# Print the original tuple
print("Original Tuple:", number_tuple)
# Convert the tuple into a list
number_list = list(number_tuple)
# Print the converted list
print("Converted List:", number_list)
print(type(number_list))
Output
Original Tuple: (5, 10, 15, 20, 25)
Converted List: [5, 10, 15, 20, 25]
<class 'list'>
Method 2: Using list comprehension
List comprehension allows you to apply an expression or operation to each element of an iterable and collect the results in a new list.
Visual Representation
Example
# Define a tuple
number_tuple = (5, 10, 15, 20, 25)
# Print the original tuple
print("Original Tuple:", number_tuple)
# Using list comprehension to convert the tuple to a list
number_list = [item for item in number_tuple]
# Print the new list
print("Converted List:", number_list)
print(type(number_list))
Output
Original Tuple: (5, 10, 15, 20, 25)
Converted List: [5, 10, 15, 20, 25]
<class 'list'>
Method 3: Using a for loop
Create an empty list and use the append() method within a for loop to add each element of the tuple, one at a time.
Example
# Define a tuple
number_tuple = (5, 10, 15, 20, 25)
# Initialize an empty list
number_list = []
# Iterate over each element in the tuple
for item in number_tuple:
# Append each element to the list
number_list.append(item)
# Print the new list
print(number_list)
print(type(number_list))
Output
[5, 10, 15, 20, 25]
<class 'list'>
Method 4: Using the map() Function
The map() function applies a specified function to each item of an iterable and converts the result into a list.
Visual Representation
Example
number_tuple = (5, 10, 15, 20, 25)
number_list = list(map(lambda x: x, number_tuple))
print(number_list)
print(type(number_list))
Output
[5, 10, 15, 20, 25]
<class 'list'>
Method 5: Using an asterisk(*) operator
The unpacking operator * allows you to unpack the elements of a tuple into a new list.
Visual Representation
Example
number_tuple = (5, 10, 15, 20, 25)
number_list = [*number_tuple]
print(number_list)
print(type(number_list))
Output
[5, 10, 15, 20, 25]
<class 'list'>
Bonus : Flattening Nested Tuples into a Single List Using itertools.chain()
Example
import itertools
number_tuple = ((5, 10), (15, 20, 25))
number_list = list(itertools.chain(*number_tuple))
print(number_list)
print(type(number_list))
Output
[5, 10, 15, 20, 25]
<class 'list'>