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 to loop through multiple lists using Python?
When working with multiple lists, Python provides several ways to iterate through them simultaneously. The most common approaches are using range() with indexing, zip() for parallel iteration, and enumerate() when you need indices.
Using range() with Indexing
The most straightforward approach uses an external iterator to keep track of indices. This method works well when all lists have the same length ?
numbers1 = [10, 12, 14, 16, 18]
numbers2 = [10, 8, 6, 4, 2]
for i in range(len(numbers1)):
print(numbers1[i] + numbers2[i])
20 20 20 20 20
Using zip() Function
The zip() function pairs elements from multiple lists and stops when the shortest list is exhausted ?
numbers1 = [10, 12, 14, 16, 18]
numbers2 = [10, 8, 6]
for a, b in zip(numbers1, numbers2):
print(a + b)
20 20 20
Using enumerate() for Index Access
When you need both the index and values, enumerate() provides a clean solution ?
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for i, name in enumerate(names):
print(f"{i}: {name} is {ages[i]} years old")
0: Alice is 25 years old 1: Bob is 30 years old 2: Charlie is 35 years old
Handling Lists of Different Lengths
For lists of different lengths, use itertools.zip_longest() with a fill value ?
from itertools import zip_longest
list1 = [1, 2, 3]
list2 = [10, 20, 30, 40, 50]
for a, b in zip_longest(list1, list2, fillvalue=0):
print(f"{a} + {b} = {a + b}")
1 + 10 = 11 2 + 20 = 22 3 + 30 = 33 0 + 40 = 40 0 + 50 = 50
Comparison
| Method | Best For | Handles Different Lengths |
|---|---|---|
range() |
Same-length lists, need indices | No (error if different) |
zip() |
Clean parallel iteration | Stops at shortest |
enumerate() |
Need both index and values | No |
zip_longest() |
Different length lists | Yes (with fill values) |
Conclusion
Use zip() for clean parallel iteration of same-length lists. Use range() when you need explicit index control. For different-length lists, use zip_longest() from itertools.
