zip() function in Python combines multiple iterables (list, dict, etc) and returns a list of tuples where each item of the iterables at the same index are paired together.
Let’s see the syntax for zip()
function before dipping into examples.
zip(iterables)
zip() parameters
Parameter | Condition | Description |
iterables | Required | One or more iterables to be paired together |
Example 1: Same number of Iterables
roll_no = [1, 2, 3] name = ["Abhishek" , "Adarsh", "Chinmay"] student = zip(roll_no, name) student_list = list(student) #Converting iterator to list print(student_list)
output
[(1, 'Abhishek'), (2, 'Adarsh'), (3, 'Chinmay')]
Example 2: Different number of Iterables
roll_no = [1, 2, 3] name = ["Carry" , "Adarsh"] student = zip(roll_no, name) student_list = list(student) #Converting iterator to list print(student_list)
output
[(1, 'Carry'), (2, 'Adarsh')]
You can see that zip() scraped the extra roll number from the list and pairs only the available pair values.
Unzip the Value Using zip()
The *
operator in python is used to unzip the zipped list. Follow the example below for a clear explanation.
roll_no = [1, 2, 3] name = ["Gourav" , "Adarsh", "Pencil Programmer"] student = zip(roll_no, name) student_list = list(student) #zipped #unzipping r, n = zip(*student_list) print('roll nos =', r) print('names =', n)
output
roll nos = (1, 2, 3) names = ('Gourav', 'Adarsh', 'Pencil Programmer')
If you have any doubts or suggestions regarding the topic then please comment below.