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
Python program to iterate over multiple lists simultaneously?
In this article, we are going to learn how to iterate over multiple lists simultaneously. This is useful when the lists contain related data. For example, one list stores names, another stores ages, and a third stores grades. By iterating over these lists simultaneously, we can access the complete information for each item.
Using zip() Function
The Python zip() function is a built-in function used to combine elements from two or more iterable objects (such as lists, tuples, etc) and returns an iterator. The resultant iterator contains tuples where the ith tuple contains the ith element from each iterable passed as argument.
Syntax
zip(iterable1, iterable2, ...)
Example 1 ? Two Lists
Let's iterate over two lists of equal length and print the corresponding items ?
cars = ["Chiron", "BMW", "RS7"]
years = [2000, 1999, 1998]
for car, year in zip(cars, years):
print(f"{car} was manufactured in the year {year}.")
Chiron was manufactured in the year 2000. BMW was manufactured in the year 1999. RS7 was manufactured in the year 1998.
Example 2 ? Three Lists
Here we iterate over three lists using the zip() function ?
names = ["Kick", "Shinchan", "Nobita"]
ages = [10, 6, 15]
grades = ['A', 'B', 'A+']
for name, age, grade in zip(names, ages, grades):
print(f"{name} with age {age} comes under {grade} category.")
Kick with age 10 comes under A category. Shinchan with age 6 comes under B category. Nobita with age 15 comes under A+ category.
Using enumerate() with zip()
The Python enumerate() function returns an enumeration object that contains pairs of index and value. You can combine it with zip() to get both the index and the paired values from multiple lists.
Syntax
enumerate(iterable, start=0)
Example
Here we use enumerate() along with zip() to get indexed results ?
car_models = ["Ciaz", "Audi", "Bugatti"]
prices = [12345, 23143, 21212]
for index, (model, price) in enumerate(zip(car_models, prices), start=1):
print(f"{index}. {model} : ${price}")
1. Ciaz : $12345 2. Audi : $23143 3. Bugatti : $21212
Handling Lists of Different Lengths
When lists have different lengths, zip() stops at the shortest list. Use itertools.zip_longest() to iterate over all elements ?
import itertools
colors = ["red", "blue", "green", "yellow"]
sizes = ["small", "large"]
# Using zip() - stops at shortest
print("Using zip():")
for color, size in zip(colors, sizes):
print(f"{color} - {size}")
print("\nUsing zip_longest():")
# Using zip_longest() - continues to longest
for color, size in itertools.zip_longest(colors, sizes, fillvalue="unknown"):
print(f"{color} - {size}")
Using zip(): red - small blue - large Using zip_longest(): red - small blue - large green - unknown yellow - unknown
Comparison
| Method | Use Case | Handles Different Lengths |
|---|---|---|
zip() |
Basic simultaneous iteration | Stops at shortest |
enumerate(zip()) |
Need index with paired values | Stops at shortest |
zip_longest() |
Handle different length lists | Continues to longest |
Conclusion
Use zip() for simultaneous iteration over multiple lists of equal length. Combine with enumerate() when you need index values, and use itertools.zip_longest() when dealing with lists of different lengths.
