Python zip()
Function
The zip() function in Python combines two or more iterables (like lists or tuples) element by element into pairs or groups. It’s extremely useful when you want to loop through multiple sequences at once.
Syntax
zip(iterable1, iterable2, ...)
Parameters:
iterable1, iterable2, ...
– Two or more iterables (lists, tuples, strings, etc.)
Returns:
- A zip object – which is an iterator of tuples, where the i-th tuple contains the i-th element from each iterable.
Example: Zipping Two Lists
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
zipped = zip(names, scores)
print(list(zipped))
[('Alice', 85), ('Bob', 90), ('Charlie', 95)]
Example: Zipping Three Iterables
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [True, False, True]
print(list(zip(a, b, c)))
[(1, 'a', True), (2, 'b', False), (3, 'c', True)]
What If Iterables Are of Unequal Length?
When iterables passed to zip()
are not of the same length, it stops at the shortest one.
x = [1, 2]
y = ['a', 'b', 'c']
print(list(zip(x, y)))
[(1, 'a'), (2, 'b')]
Use Case: Creating a Dictionary
keys = ['id', 'name', 'age']
values = [101, 'Alice', 25]
person = dict(zip(keys, values))
print(person)
{'id': 101, 'name': 'Alice', 'age': 25}
Looping with zip()
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Alice scored 85
Bob scored 90
Charlie scored 95
Unzipping Using *
Operator
You can reverse a zipped object using the unpacking operator *
:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
a, b = zip(*pairs)
print(a)
print(b)
(1, 2, 3)
('a', 'b', 'c')
Common Mistakes
- Forgetting to convert the zip object to a list when printing:
print(zip(...))
will just show the object type. - Expecting
zip()
to handle different lengths – it doesn't pad, it truncates.
Interview Tip
zip()
is frequently used in data pairing, matrix manipulation, and transforming data between structures. Be ready to combine or unzip data structures in questions.
Summary
zip()
combines multiple iterables into tuples.- Stops when the shortest iterable is exhausted.
- Great for pairing keys and values, parallel looping, and restructuring data.
Practice Problem
Given two lists of student names and their grades, print each student with their grade using zip()
.
students = ["Ravi", "Meena", "Arjun"]
grades = ["A", "B", "A+"]
for student, grade in zip(students, grades):
print(f"{student} got grade {grade}")