🤐

How to Use Zip in Python

PythonBeginner

Combine multiple iterables with zip.

Code Example

Python
# Basic zip
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

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

# Create dictionary
name_age_dict = dict(zip(names, ages))
print(f"\nDictionary: {name_age_dict}")

# Multiple iterables
names = ["Alice", "Bob"]
ages = [25, 30]
cities = ["NYC", "LA"]

for name, age, city in zip(names, ages, cities):
    print(f"{name}, {age}, from {city}")

# Unzip
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(f"\nNumbers: {numbers}")
print(f"Letters: {letters}")

# With different lengths
short = [1, 2]
long = [10, 20, 30, 40]
print(f"\nZip stops at shortest: {list(zip(short, long))}")

# Using itertools.zip_longest for all items
from itertools import zip_longest
print(f"With zip_longest: {list(zip_longest(short, long, fillvalue=0))}")

Explanation

zip() combines iterables element-wise. Stops at shortest iterable. Use * to unzip. Use zip_longest() to include all items.

Related Tutorials