Navigation

Python

How to Use zip() for Parallel Iteration

Use Python's zip() function to iterate over multiple sequences simultaneously. Combine lists, create dictionaries, and handle unequal lengths.

Table Of Contents

Problem

You need to iterate over multiple lists or sequences at the same time, accessing corresponding elements from each sequence.

Solution

# Basic zip usage
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['NYC', 'LA', 'Chicago']

for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} years old and lives in {city}")

# Create dictionary from two lists
keys = ['name', 'age', 'occupation']
values = ['John', 28, 'Engineer']
person = dict(zip(keys, values))
print(person)  # {'name': 'John', 'age': 28, 'occupation': 'Engineer'}

# Transpose matrix (swap rows and columns)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
transposed = list(zip(*matrix))
print(transposed)  # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

# Handle unequal length sequences (zip stops at shortest)
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
result = list(zip(list1, list2))
print(result)  # [(1, 'a'), (2, 'b'), (3, 'c')]

# Use itertools.zip_longest for unequal lengths
from itertools import zip_longest

result = list(zip_longest(list1, list2, fillvalue='N/A'))
print(result)  # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'N/A'), (5, 'N/A')]

# Enumerate with multiple sequences
scores = [85, 92, 78, 96]
subjects = ['Math', 'Science', 'English', 'History']

for i, (score, subject) in enumerate(zip(scores, subjects)):
    print(f"{i+1}. {subject}: {score}%")

# Unzip (separate combined data)
paired_data = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*paired_data)
print(numbers)  # (1, 2, 3)
print(letters)  # ('a', 'b', 'c')

# Calculate element-wise operations
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

# Add corresponding elements
sums = [a + b for a, b in zip(x, y)]
print(sums)  # [6, 8, 10, 12]

# Find differences
differences = [abs(a - b) for a, b in zip(x, y)]
print(differences)  # [4, 4, 4, 4]

# Compare sequences element by element
def compare_lists(list1, list2):
    matches = []
    for a, b in zip(list1, list2):
        matches.append(a == b)
    return matches

result = compare_lists([1, 2, 3], [1, 5, 3])
print(result)  # [True, False, True]

# Process multiple files simultaneously
filenames = ['data1.txt', 'data2.txt', 'data3.txt']
headers = ['Name', 'Age', 'City']

for filename, header in zip(filenames, headers):
    print(f"Processing {filename} with header: {header}")

Explanation

zip() combines multiple iterables into tuples, stopping when the shortest sequence is exhausted. Use zip(*sequence) to unzip data back into separate sequences.

For sequences of different lengths, use itertools.zip_longest() with a fillvalue. This pattern is essential for parallel data processing and matrix operations.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Python