Explain Codes LogoExplain Codes Logo

How do I iterate through two lists in parallel?

python
iterators
list-comprehension
zip-function
Alex KataevbyAlex KataevΒ·Jan 6, 2025
⚑TLDR

To achieve parallel iteration in Python, employ zip():

# Because printing is the biggest superpower in Python πŸ¦Έβ€β™‚οΈ for item1, item2 in zip(list1, list2): print(item1, item2)

Note that zip() terminates when it encounters the finish line of the shortest list. For handling uneven races/lists, get the aid of itertools.zip_longest():

from itertools import zip_longest # Note the use of 'None' as fillvalue. Because null is not just a concept, it's a lifestyle! πŸ§˜β€β™‚οΈ for item1, item2 in zip_longest(list1, list2, fillvalue='None'): print(item1, item2)

Unequal-sized lists? No problem!

If the length of your lists don't exactly see eye-to-eye, and you prefer to dodge None for absent elements, design your own custom solution to handle this like so:

# All hail Python for teaching us how to yield πŸ‘‘ def custom_parallel_iterator(list1, list2, default='None'): for i in range(max(len(list1), len(list2))): yield (list1[i] if i < len(list1) else default, list2[i] if i < len(list2) else default) for item1, item2 in custom_parallel_iterator(list1, list2): print(item1, item2)

Wedlock for dictionaries and lists

Need to construct dictionaries from list pairs that have taken a liking to each other? zip() is your friendly neighborhood marriage registrar:

# All it takes is a ring (or a curly brace) to bind them together πŸ’ keys = ['one', 'two', 'three'] values = [1, 2, 3] combined_dict = {k: v for k, v in zip(keys, values)}

In instances of lists of tuples looking to merge, zip() along with the * operator (the Harry Potter of Python) assist:

# Turn that asterisk key into your magic wand ✨ list_of_tuples = zip(*[(1, 'one'), (2, 'two'), (3, 'three')]) keys, values = list_of_tuples

Maximizing performance

Cruise on the performance highway by clubbing list comprehension with zip(), most noticeable when dealing with monumental datasets. Remember, size does matter....for large datasets:

# Fast and Furious: The Python edition πŸš—πŸ’¨ combined_list = [f(item1, item2) for item1, item2 in zip(list1, list2)]

Custom needs? Custom pairing!

For scenarios that require a more refined control over iteration, write your own custom pairing functions:

# Custom Python scripts, because off-the-stakes isn't for everyone πŸ‘•πŸ‘– def custom_pairing(list1, list2, predicate): for item1, item2 in zip(list1, list2): if predicate(item1, item2): yield (item1, item2) for item1, item2 in custom_pairing(list1, list2, lambda x, y: type(x) == type(y)): print(f"Paired: {item1} and {item2}")

Instances when tomatoes aren't fruits

Sometimes, zip() might not be your knight in shining armor if:

  • Your capacious lists are devouring all your memory, especially in Python 2 where zip() turns into a huuuge list of tuples. In Python 3 though, it's an iterator and not a memory glutton.
  • You're handling more than two lists. zip() can deal with multiple lists but starts to look messier than your hair in the morning with increasing lists.
  • You need to keep track of your iteration. enumerate() fits the bill perfectly in such cases:
# Apparently, 0, 1, 2, 3... are more than just numbers πŸ€” for index, (item1, item2) in enumerate(zip(list1, list2)): print(f"Index {index}: {item1} & {item2}")

Dial itertools for advanced iteration services

When you seek powerful and versatile iteration patterns, ring up itertools. This module offers a multitude of iterator-building functions, giving you more control to rule your iteration kingdom.