Convert Tuple to List in Python
In Python, tuples and lists are commonly used data structures, but they have different properties:
- Tuples are immutable: their elements cannot be changed after creation.
- Lists are mutable: they support adding, removing, or changing elements.
Sometimes, you may need to convert a tuple to a list for further manipulation.
For example:
tup = (1, 2, 3, 4)
To convert this into a list:
[1, 2, 3, 4]
Let's explore various methods to perform this conversion.
1. Using list() Constructor
The most straightforward and efficient way to convert a tuple into a list is by using the list() constructor.
tup = (1, 2, 3, 4)
a = list(tup)
print(a)
Output
[1, 2, 3, 4]
Explanation:
- list(tup) takes the tuple t as input and returns a new list containing the same elements.
- Internally, it iterates over the tuple and stores each element in a list.
2. Using List Comprehension
List comprehension provides a clean and Pythonic way to convert a tuple to a list.
tup = (1, 2, 3, 4)
a = [item for item in tup]
print(a)
Output
[1, 2, 3, 4]
Explanation:
- list comprehension loops through each element item in the tuple tup.
- It collects each item into a new list.
3. Using Unpacking Operator *
The unpacking operator * can be used to unpack the elements of a tuple into a list.
tup = (1, 2, 3, 4)
a = [*tup]
print(a)
Output
[1, 2, 3, 4]
Explanation:
- * operator unpacks each item from the tuple.
- Placing it inside square brackets creates a list from the unpacked element.
4. Using for Loop (Manual Conversion)
A for loop can be used to manually convert a tuple into a list by iterating over its elements.
tup = (1, 2, 3, 4)
a = []
for item in tup:
a.append(item)
print(a)
Output
[1, 2, 3, 4]
Explanation:
- An empty list is initialized to store the elements.
- The loop iterates through the tuple, appending each element to the list.
5. Using map()
The map() function, combined with the identity function lambda x: x, can also convert a tuple into a list.
tup = (1, 2, 3, 4)
a = list(map(lambda x: x, tup))
print(a)
Output
[1, 2, 3, 4]
Explanation:
- map(lambda x: x, tup) applies the identity function to each element.
- It produces a map object containing the same elements as the tuple.
- list() then converts this object to a list.
Related articles: