W3docs

How do I iterate through two lists in parallel?

You can use the zip() function to iterate through two lists in parallel.

You can use the zip() function to iterate through two lists in parallel. The zip() function takes two or more lists as arguments and returns an iterator that generates tuples containing the elements from each list at corresponding positions. By default, zip() stops when the shortest input iterable is exhausted. Here's an example:

Using the zip function in Python

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

for item1, item2 in zip(list1, list2):
    print(item1, item2)

# Output:
# 1 a
# 2 b
# 3 c

Alternatively, you can also use itertools.zip_longest() or itertools.product() depending on the requirement.

itertools.zip_longest(iter1, iter2, fillvalue=None) returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterators. Unlike zip(), this function continues until the longest input iterable is exhausted, filling missing values with fillvalue (defaulting to None).

itertools.product(*iterables, repeat=1) returns an iterator of the Cartesian product of the input iterables. For example, product([1, 2], ['a', 'b']) yields (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b').