Python: How to loop through 2 lists in parallel (3 ways)

Updated: June 19, 2023 By: Khue Post a comment

This concise, example-based article will walk you through some different ways to iterate over 2 Python lists in parallel. Without more delays, let’s get started.

Using the zip() function

The zip() function combines the elements of 2 or more lists into tuples, allowing you to iterate over them in parallel. It will stop when the shortest list is exhausted and ignore any remaining elements in the longer list.

Example:

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']

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

Output:

1 a
2 b
3 c
4 d
5 e

Using enumerate() with indexing

This approach uses the enumerate() function along with indexing to access corresponding elements in both lists.

Code example:

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

for index, item1 in enumerate(list1):
    if index < len(list2):
        item2 = list2[index]
        print(item1, item2)

Output:

1 a
2 b
3 c

The advantage of this approach is that it allows for more flexibility in handling lists of different lengths, as you have control over the indexing.

Using the itertools.zip_longest() function

zip_longest() is a function from the itertools module that allows you not only to iterate over multiple iterables in parallel but also to fill in missing values with a specified fill value when the iterables are of different lengths. While the zip() function stops immediately when the shortest list is exhausted, the itertools.zip_longest() function will go forward until the end of the longest list.

Example:

from itertools import zip_longest

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

for item1, item2 in zip_longest(list1, list2, fillvalue="Sling Academy"):
    print(item1, item2)

Output:

1 a
2 b
3 c
4 Sling Academy
5 Sling Academy

That’s it. Happy coding!