Iterate over Two Lists with Different Lengths in Python
Iterating over two lists of different lengths is a common scenario in Python. However, we may face challenges when one list is shorter than the other. Fortunately, Python offers several methods to handle such cases, ensuring that our code is both readable and efficient.
Using zip() function - Loop until shortest list ends
zip()
function is one of the simplest ways to iterate over two or more lists. It pairs elements by their positions but stops when the shorter list ends.
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd', 'e']
# zip() pairs elements from each list by their index positions
for item1, item2 in zip(a, b):
print(item1, item2)
Table of Content
Using itertools.zip_longest()
The itertools module has itertools.zip_longest() function, which is ideal for iterating over lists of different lengths. This function fills the shorter list with a specified value (default is None) to ensure that both lists can be traversed completely.
from itertools import zip_longest
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd', 'e']
# Iterates over both lists, filling missing values with None
for item1, item2 in zip_longest(a, b, fillvalue=None):
print(item1, item2)
# comprehensive code for above loop
# result = [(a, b) for a, b in zip_longest(x, y, fillvalue=None)]
Output
1 a 2 b 3 c None d None e
Here is the list of all methods to Iterate over Two lists with different lengths in Python.
Using for Loop with range() and len()
For full control over how you iterate over two lists of different lengths, you can use a for loop.
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c', 'd', 'e']
# Determine the maximum length between the two lists
max_len = max(len(l1), len(l2))
# Iterate over a range from 0 to max_length - 1
for i in range(max_len):
# Get the element from x at index i if it exists, otherwise use None
item1 = l1[i] if i < len(l1) else None
# Get the element from y at index i if it exists, otherwise use None
item2 = l2[i] if i < len(l2) else None
print(item1, item2)
Output
1 a 2 b 3 c None d None e
Using enumerate() - Loop until shortest list ends
enumerate() function can be combined with manual checks for lengths to provide more control over iteration when working with two lists of different lengths.
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c', 'd', 'e']
# Iterate over the length of x (the shorter list) using enumerate
for i, _ in enumerate(l1):
# Check if within bounds of y, but this is a logical error
a = l1[i] if i < len(l2) else None
# Get element from y at index i
b = l2[i]
print(a, b)
Output
1 a 2 b 3 c