Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I iterate through two lists in parallel in Python?
In Python, iterating through two or more lists in parallel is a common task. Python provides several methods to achieve this, each with different behaviors for handling lists of unequal lengths.
Using range() with Index-Based Access
The most basic approach uses range() with the len() function to iterate through both lists using indices ?
Example
When both lists have the same length ?
letters = ['a', 'b', 'c', 'd', 'e']
numbers = [97, 98, 99, 100, 101]
length = len(letters) # Assuming both lists have same length
for i in range(length):
print(letters[i], numbers[i])
a 97 b 98 c 99 d 100 e 101
Handling Lists of Different Lengths
When lists have different lengths, use the minimum length to avoid IndexError ?
numbers = [1, 2, 3, 4, 5, 6, 7]
letters = ['a', 'b', 'c']
length = min(len(numbers), len(letters))
for i in range(length):
print(numbers[i], letters[i])
1 a 2 b 3 c
Using zip() Function
The zip() function is the most Pythonic way to iterate through multiple lists. It automatically stops when the shortest list is exhausted ?
numbers = [1, 2, 3, 4, 5, 6, 7]
letters = ['a', 'b', 'c']
for num, letter in zip(numbers, letters):
print(num, letter)
1 a 2 b 3 c
Using itertools.zip_longest()
When you need to iterate through all elements of the longest list, use zip_longest(). Missing values are filled with None by default ?
Syntax
zip_longest(iterable1, iterable2, fillvalue=None)
Example
import itertools
numbers = [1, 2, 3, 4, 5, 6, 7]
letters = ['a', 'b', 'c']
for num, letter in itertools.zip_longest(numbers, letters):
print(num, letter)
1 a 2 b 3 c 4 None 5 None 6 None 7 None
Iterating Three Lists
You can iterate through any number of lists simultaneously ?
import itertools
numbers = [1, 2, 3, 4, 5, 6, 7]
letters = ['a', 'b', 'c', 'd', 'e']
symbols = [10, 11, 12, 13]
for num, letter, symbol in itertools.zip_longest(numbers, letters, symbols):
print(num, letter, symbol)
1 a 10 2 b 11 3 c 12 4 d 13 5 e None 6 None None 7 None None
Comparison
| Method | Behavior | Best For |
|---|---|---|
range() |
Stops at minimum length | When you need indices |
zip() |
Stops at shortest list | Most common use cases |
zip_longest() |
Continues to longest list | Processing all elements |
Conclusion
Use zip() for most parallel iteration tasks as it's clean and efficient. Use zip_longest() when you need to process all elements from the longest list. Use range() only when you specifically need access to indices.
