- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Unzip a list of Python Tuples
Python is a programming language used world wide for different purposes such as web development, data science, machine learning and to perform many different processes with automation. Tuple is a very useful feature of python which helps to stores data from multiple data sets like dictionary, list etc. together on one level. In this article we learn about the different methods that can be used to unzip a list of python tuples.
Different Methods to Unzip a List of Python Tuples
List Comprehension
List comprehension is used to check over each element present in the list one by one. In this method with the help of list comprehension we will unzip a list of tuples. Let’s take a example to understand it in a better way:
Example
Places = [('Ahmedabad', 'Gujarat'), ('Hyderabad', 'Telangana'), ('Silchar', 'Assam'), ('Agartala', 'Tripura'), ('Namchi', 'Sikkim')] # The input of tuples is given City, States = zip(*Places) # The zip function of list comprehension separate the data into different cities and states print(City) print(States)
Output
The output of the above example will be as follows :
('Ahmedabad', 'Hyderabad', 'Silchar', 'Agartala', 'Namchi') ('Gujarat', 'Telangana', 'Assam', 'Tripura', 'Sikkim')
Itertools
Itertools is mainly used to iterate over elements in the data in loops. This method is more preferable in cases where there are huge number of tuples with lot of data. Let’s take an example to understand it in a better way:
Example
from itertools import zip_longest # Do not forget to import itertools or else error might occur Places = [('Ahmedabad', 'Gujarat'), ('Hyderabad', 'Telangana'), ('Silchar', 'Assam'), ('Agartala', 'Tripura'), ('Namchi', 'Sikkim')] # The input of tuples is given City, State = zip_longest(*Places) # We use zip_longest so that the tuples which are not same in length can also be unzipped City = [City for City in City if City is not None] # The different lists formed might consist of `none` value for missing element State = [State for State in State if State is not None] # The list comprehension to maintain the same length and remove the none values print(City) print(State)
Output
The Output of the above example will be as follows:
('Ahmedabad', 'Hyderabad', 'Silchar', 'Agartala', 'Namchi') ('Gujarat', 'Telangana', 'Assam', 'Tripura', 'Sikkim')
Loop Method
This method was used when different features were not introduced in python. It is one of the simplest and basic method to unzip the list of tuples. Let’s take an example to understand it in a better way:
Example
Places = [('Ahmedabad', 'Gujarat'), ('Hyderabad', 'Telangana'), ('Silchar', 'Assam'), ('Agartala', 'Tripura'), ('Namchi', 'Sikkim')] # The input of tuples is given Cities = [] States = [] for City, State in Places: # We check each value in the list and then extract the different city and state element Cities.append(City) States.append(State) print(Cities) print(States)
Output
The output of the above example is as follows :
('Ahmedabad', 'Hyderabad', 'Silchar', 'Agartala', 'Namchi') ('Gujarat', 'Telangana', 'Assam', 'Tripura', 'Sikkim')
Numpy
This feature is mainly useful when the list of tuples contains different numerical data. We can easily use the function of numpy in such a situation. Let’s take an example to understand it in a better way:
Example
import numpy as np # DO not forget to import numpy or else error might occur Places = [('Gujarat', 31), ('Punjab', 237), ('Assam', 33), ('Tripura', 14), ('Sikkim', 6)] # The input of tuples is given States, number_of_cities = np.array(Places).T.tolist() # We will use array operation to unzip the data #np.array will help us convert the tuple into array and .T will help us to unzip and separate the data and tolist will convert into list print(States) print(number_of_cities)
Output
The output of the above example will be as follows:
['Gujarat', 'Punjab', 'Assam', 'Tripura', 'Sikkim'] ['31', '237', '33', '14', '6']
Panda Data Frame
This is a very advanced method to unzip the data and used only in cases when there is a high accuracy required in huge amount of data. Let’s take an example to understand it in a better way:
Example
import pandas as pd # Do not forget to import pandas data frame or else error might occur Places = [('Ahmedabad', 'Gujarat'), ('Hyderabad', 'Telangana'), ('Silchar', 'Assam'), ('Agartala', 'Tripura'), ('Namchi', 'Sikkim')] # The input of tuples is given df = pd.DataFrame(Places, columns=['City', 'State']) # The list is first converted into pandas data frame with the help of pd.dataframe which help us to have access to elements separately Cities = df['City'].tolist() #tolist will help to convert these dataframes back into standard lists States = df['State'].tolist() print(Cities) print(States)
Output
The Output of the above example will be as follows:
('Ahmedabad', 'Hyderabad', 'Silchar', 'Agartala', 'Namchi') ('Gujarat', 'Telangana', 'Assam', 'Tripura', 'Sikkim')
Operator Module
We will use the functions of operator module to unzip a list of tuples. This method is also a complex method and used in rare cases. Lets take an example to understand it in a better way:
Example
from operator import itemgetter # Do not forget to import operator module or else error might occur Places = [('Ahmedabad', 21), ('Hyderabad', 32), ('Silchar', 43), ('Agartala', 24), ('Namchi', 21)] # The input of tuples is given Cities, people = map(list, zip(*map(itemgetter(0), Places))), map(itemgetter(1), Places) people = list(people)# itemgetter 0 & 1 will used to get the city and state element respectively and the map function helps them to find the elements in the places list and with the help of zip we will unzip the list print(people)
Output
The output of the above example will be as follows:
[21, 32, 43, 24, 21]
Conclusion
To become an efficient programmer, one must have knowledge about the different methods that can be used to unzip a list of tuples. Different method can be used as per convenience and field of application. All the different methods that can be used are mentioned in the above article