Unzipping a list of tuples means unzipping a tuple (or, more accurately, a sequence of tuples like a list of tuples) is the process of separating the elements within the tuples into separate sequences.
You can the built-in zip() function in combination with the * operator to unzip a list of tuples in Python. The zip() function accepts multiple lists as arguments and returns an iterator of tuples, where the nth tuple contains the nth element from each of the argument sequences or iterables.
Then, use the * operator to unpack the tuples in the iterator and pass the elements as separate arguments to the function.
list_of_tuples = [("a", 19), ("c", 46)] # Using zip() with * to unzip the list list_a_obj, list_b_obj = zip(*list_of_tuples) # Converting the results to lists list_a = list(list_a_obj) list_b = list(list_b_obj) print(list_a) print(list_b)
Output
['a', 'c'] [19, 46]
In this example, we first initialized a list of tuples. Each tuple contains two elements. There are a total of two tuples in the list.
Then, we used the zip() function with the * operator to unzip the list, which returns two list-objects.
In the final step, we used the list() function was then used to convert the iterator into lists of tuple values.
The zip(*) approach is more Pythonic and efficient. I highly recommend using this approach.
Using List comprehension
The list comprehension approach is not as dynamic as zip(*) and is inefficient. Nonetheless, it will help you unzip a list. Use list comprehensions for unzipping only if you have a very specific reason to avoid zip(*), such as a strict coding style guide that prohibits it.
list_of_tuples = [("a", 19), ("c", 46)] # Using list comprehension to unzip list_a = [x[0] for x in list_of_tuples] list_b = [x[1] for x in list_of_tuples] print(list_a) print(list_b)
Output
['a', 'c'] [19, 46]
That’s it!