‹‹

Processing iterators in parallel

Nov 03, 2021

Read time: 1 minute

Use zip

zip(*iterables, strict=False)

Iterate over several iterables in parallel, producing tuples with an item from each one.

Examples

Without zip

countries = ["Kenya", "Tanzania", "Uganda"]
capitals = ["Nairobi", "Dodoma", "Kampala"]

print("=== using range ===")
for i in range(len(countries)):
    country, capital = countries[i], capitals[i]
    print(f"Country: {country}, Capital: {capital}")

print("=== using enumerate ===")
for i, country in enumerate(countries):
    country, capital = countries[i], capitals[i]
    print(f"Country: {country}, Capital: {capital}")

Output:

=== using range ===
Country: Kenya, Capital: Nairobi
Country: Tanzania, Capital: Dodoma
Country: Uganda, Capital: Kampala

=== using enumerate ===
Country: Kenya, Capital: Nairobi
Country: Tanzania, Capital: Dodoma
Country: Uganda, Capital: Kampala

With zip

print("=== using zip ===")
for country, capital in zip(countries, capitals):
    print(f"Country: {country}, Capital: {capital}")

Output:

=== using zip ===
Country: Kenya, Capital: Nairobi
Country: Tanzania, Capital: Dodoma
Country: Uganda, Capital: Kampala

Same result, but more elegant.

🏷