The zip() function in Python is a built-in function used to combine multiple iterable objects (such as lists, tuples, or strings) into a single iterator of tuples. Each tuple contains elements from the corresponding position of the given iterables.
In simple terms, zip() pairs elements from different sequences together based on their index position.
The function is very useful when we want to iterate over multiple sequences simultaneously.
zip(iterable1, iterable2, ..., iterableN)
Parameters
Return Value
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
result = zip(numbers, letters)
print(list(result))
Output
[(1, 'a'), (2, 'b'), (3, 'c')]
Explanation
(1, 'a')(2, 'b')(3, 'c')zip() in a Loopnames = ["Rahul", "Amit", "Priya"]
marks = [85, 90, 88]
for name, mark in zip(names, marks):
print(name, mark)
Output
Rahul 85
Amit 90
Priya 88
Explanation
zip() pairs each student's name with their corresponding marks.a = [1, 2, 3, 4]
b = ['x', 'y']
print(list(zip(a, b)))
Output
[(1, 'x'), (2, 'y')]
Explanation
zip() stops when the shortest iterable is exhausted.zip() with Three Iterablesnames = ["Rahul", "Amit", "Priya"]
marks = [85, 90, 88]
grades = ["A", "A+", "A"]
print(list(zip(names, marks, grades)))
Output
[('Rahul', 85, 'A'), ('Amit', 90, 'A+'), ('Priya', 88, 'A')]
Explanation
zip()zip() can also be used to separate paired elements back into individual sequences.
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)
Output
(1, 2, 3)
('a', 'b', 'c')
Explanation
* operator unpacks the list of tuples before applying zip().subjects = ["Math", "Physics", "Chemistry"]
marks = [80, 75, 90]
student_record = dict(zip(subjects, marks))
print(student_record)
Output
{'Math': 80, 'Physics': 75, 'Chemistry': 90}
Explanation
zip() combines subjects and marks.dict() converts them into a dictionary.zip()zip() is a built-in Python function used to combine multiple iterables.