Learn how to use Python's zip() function with clear examples. Understand syntax, basic usage, real-world applications, and advanced techniques for combining iterables efficiently.
zip()
?The zip()
function is a built-in Python function that combines elements from multiple iterables (like lists, tuples, etc.) into a single iterable of tuples. It pairs up elements from each input iterable that are at the same position.
zip(*iterables)
*iterables
: One or more iterables to be zipped together (like lists, tuples, strings, etc.)names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# Zip the two lists together
zipped = zip(names, ages)
# Convert the zip object to a list to see the contents
print(list(zipped))
Output:
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
zip()
returns an iterator (zip object), not a listlist()
Imagine you’re managing a classroom with students, their grades, and their attendance:
students = ['Emma', 'Liam', 'Olivia']
scores = [85, 92, 78]
attendance = [95, 88, 92]
# Create a report combining all information
report = list(zip(students, scores, attendance))
# Print individual student reports
for name, score, attd in report:
print(f"{name}: Score = {score}%, Attendance = {attd}%")
Output:
Emma: Score = 85%, Attendance = 95%
Liam: Score = 92%, Attendance = 88%
Olivia: Score = 78%, Attendance = 92%
zipped_data = [('Emma', 85), ('Liam', 92), ('Olivia', 78)]
names, scores = zip(*zipped_data)
print(names) # ('Emma', 'Liam', 'Olivia')
print(scores) # (85, 92, 78)
list1 = [1, 2, 3]
list2 = ['a', 'b']
print(list(zip(list1, list2))) # [(1, 'a'), (2, 'b')]
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
person = dict(zip(keys, values))
print(person)
# {'name': 'Alice', 'age': 25, 'gender': 'Female'}
The zip()
function is a powerful tool for working with multiple sequences in Python, making your code more concise and readable.