The task of unzipping a list of tuples in Python involves separating the elements of each tuple into individual lists, based on their positions. For example, given a list of tuples like [('a', 1), ('b', 4)], the goal is to generate two separate lists: ['a', 'b'] for the first elements and [1, 4] for the second elements.
Using zip()
The most efficient way to unzip a list of tuples is by using the built-in zip() function in combination with the unpacking operator *. This method allows us to "unzip" the list of tuples into separate lists in a single line.
x = [('a', 1), ('b', 4)]
# Using zip() with * to unzip the list
a, b = zip(*x)
# Convert the results to lists
a = list(a)
b = list(b)
print(a)
print(b)
Output
['a', 'b'] [1, 4]
Explanation:* operator unpacks the list of tuples and the zip() function then pairs the corresponding elements into separate lists.
Table of Content
Using List Comprehension
List comprehension provides a more manual yet elegant way to unzip a list of tuples. By iterating through each tuple and extracting the first and second elements, we can create two new lists.
c = [('a', 1), ('b', 4)]
# Using list comprehension to unzip
a = [x[0] for x in c]
b = [x[1] for x in c]
print(a)
print(b)
Output
['a', 'b'] [1, 4]
Explanation : list comprehension iterates through the list of tuples (c) and extracts the first and second elements of each tuple into separate lists.
Using For Loop
If we prefer a more explicit and manual approach, using a for loop to iterate through the tuples is a great alternative. This method is simple but might not be as concise or efficient as the previous methods.
c = [('a', 1), ('b', 4)]
# Using a for loop to unzip
a = []
b = []
for item in c:
a.append(item[0]) # Add the first item of each tuple to list a
b.append(item[1]) # Add the second item of each tuple to list b
print(a)
print(b)
Output
['a', 'b'] [1, 4]
Explanation: In this method, we initialize two empty lists, a and b. Then, we loop through each tuple in the list c and append the first and second elements of the tuple to the respective lists .