Python enumerate & zip Examples
Short, runnable programs that show python enumerate() and zip() in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python enumerate() and zip() lesson.
1Reporting positions with enumerate
When you need to say which item matched, enumerate gives you the position for free. With start=1 the day numbers read naturally.
temps = [18, 24, 31, 22, 35, 28]
for day, temp in enumerate(temps, start=1):
if temp > 30:
print(f"Day {day} was hot: {temp} degrees")Expected outputDay 3 was hot: 31 degrees
Day 5 was hot: 35 degrees
2Three lists in step: a shopping bill
Item names, prices and quantities live in three lists that line up by position. One zip loop reads all three at once.
items = ["pen", "notebook", "stapler"]
prices = [1.5, 4.0, 7.25]
quantities = [10, 3, 2]
total = 0
for item, price, qty in zip(items, prices, quantities):
line = price * qty
total += line
print(f"{item}: {qty} x {price} = {line}")
print("Total:", total)Expected outputpen: 10 x 1.5 = 15.0
notebook: 3 x 4.0 = 12.0
stapler: 2 x 7.25 = 14.5
Total: 41.5
3A numbered leaderboard: enumerate around zip
zip makes the (player, points) pairs and enumerate puts a place number in front. The inner pair is unpacked with its own parentheses.
players = ["Mia", "Noah", "Zoe"]
points = [310, 275, 190]
for place, (player, pts) in enumerate(zip(players, points), start=1):
print(f"#{place} {player}: {pts} points")Expected output#1 Mia: 310 points
#2 Noah: 275 points
#3 Zoe: 190 points
4A lookup table from two lists
dict(zip(keys, values)) turns two parallel lists into a dictionary, so you can look a value up by its key instead of searching.
countries = ["France", "Japan", "Brazil"]
capitals = ["Paris", "Tokyo", "Brasilia"]
capital_of = dict(zip(countries, capitals))
print(capital_of)
print("Capital of Japan:", capital_of["Japan"])Expected output{'France': 'Paris', 'Japan': 'Tokyo', 'Brazil': 'Brasilia'}
Capital of Japan: Tokyo
5Uneven lists: zip versus zip(strict=True)
Plain zip quietly stops at the shortest list. With strict=True the mismatch raises a ValueError. The try/except part (covered in a later lesson) only lets the program print the error message instead of stopping.
names = ["Asha", "Ben", "Chen"]
scores = [88, 92]
print(list(zip(names, scores)))
try:
for name, score in zip(names, scores, strict=True):
print(name, score)
except ValueError as error:
print("Caught:", error)Expected output[('Asha', 88), ('Ben', 92)]
Asha 88
Ben 92
Caught: zip() argument 2 is shorter than argument 1
6Comparing neighbours with zip(items, items[1:])
Zipping a list with a copy of itself shifted by one gives you each value next to the one after it. It stops after the last pair, so there is no index to run off the end.
prices = [100, 104, 103, 110, 108]
for today, tomorrow in zip(prices, prices[1:]):
change = tomorrow - today
print(f"{today} -> {tomorrow}: {change:+}")Expected output100 -> 104: +4
104 -> 103: -1
103 -> 110: +7
110 -> 108: -2
Practise next
Python enumerate() and zip() exercises → Back to the lesson
Python for Loops examplesPython range() Function examplesPython Dictionaries examplesPython List Comprehensions examples