Python zip() method returns the zip object, which is an iterator of tuples. The zip() method creates an iterator that will aggregate items from two or more iterables.
How to Unzip List of Tuples in Python
To unzip a list of tuples means it returns the new list of tuples where each tuple consists of the identical items from each original tuple.
To unzip a list of tuples in Python, you can use one of the following ways.
- Using zip() and * operator
- Using List Comprehension
#1: Using zip() and * operator
The * operator unzips the tuples into independent lists. Combination with the Python zip() method, it will help us to unzip the list of tuples.
# app.py data_list = [('Harry', 17), ('Hermione', 17), ('Ginny', 16)] print('Original List: ', str(data_list)) unzipped_list = list(zip(*data_list)) print('Unzipped list', unzipped_list)
Output
Original List: [('Harry', 17), ('Hermione', 17), ('Ginny', 16)] Unzipped list [('Harry', 'Hermione', 'Ginny'), (17, 17, 16)]
In this example, we have defined a list of three tuples that we need to unzip, and then we print the list. In the next step, we have used the combination of zip() and * operator to unzip the tuple and make an iterator, and then we convert that iterator into a list using the list() method.
By inserting * before the list’s name, we can iterate through each item in the list and unzip the tuple.
#2: Using List Comprehension
List Comprehension is the most logical approach to perform the task of unzipping but not suggested because it returns the list of lists and not a list of tuples. But it does unzip the tuples. So Let’s have a look at the following code example.
# app.py data_list = [('Harry', 17), ('Hermione', 17), ('Ginny', 16)] print('Original List: ', str(data_list)) unzipped_list = [[i for i, j in data_list], [j for i, j in data_list]] print('Unzipped list', unzipped_list)
Output
Original List: [('Harry', 17), ('Hermione', 17), ('Ginny', 16)] Unzipped list [['Harry', 'Hermione', 'Ginny'], [17, 17, 16]]
In this example, we have used list comprehension to unzip the list of tuples and return lists.
Conclusion
Converting Python list to String, List to Tuple, List to JSON, List to CSV are among the most common tasks in Python. The more data you get, the more conversion you need from one to another. If you want to unzip your list of tuples, you use the combination of zip() method and * operator.