Now that you're comfortable with lists and their methods, you'll notice two loop problems coming up again and again:
You need both the position and the item while looping, for example to print a numbered list.
You have two (or more) related lists, like student names and their marks, and you want to walk through them together.
You can solve both with range(len()) and indexes, but Python has two built-in functions that do it more cleanly: enumerate() and zip(). You already saw a quick preview of enumerate() in the Lists chapter. Here we'll learn both properly.
The Problem with range(len())
names = ["Asha", "Ravi", "Meena"]
marks = [91, 85, 78]
for i in range(len(names)):
print(i + 1, names[i], marks[i])Output:
1 Asha 91
2 Ravi 85
3 Meena 78It works, but there's a lot of noise: range(len(...)), names[i], marks[i], and i + 1. Each one is a chance for an off-by-one or wrong-index bug. By the end of this chapter, you'll write the same loop like this:
for rank, (name, mark) in enumerate(zip(names, marks), start=1):
print(rank, name, mark)Let's build up to it step by step.
Part 1: enumerate()
enumerate(iterable, start=0)takes any iterable (list, string, range, ...) and gives back its items one at a time, each paired with a counter. The counter starts atstart, which is0by default.
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)Output:
0 apple
1 banana
2 mangoWhat enumerate() Actually Produces
Each step of enumerate() produces a pair (counter, item). You can see all the pairs at once by converting it to a list:
fruits = ["apple", "banana", "mango"]
print(list(enumerate(fruits)))Output:
[(0, 'apple'), (1, 'banana'), (2, 'mango')]The round brackets (0, 'apple') are a tuple, a fixed-size group of values. We'll study tuples in the very next chapter. For now, think of each one as a pair.
In the loop, for index, fruit in ... unpacks each pair into two variables:
enumerate(["apple", "banana", "mango"])
step 1 -> (0, "apple") -> index = 0, fruit = "apple"
step 2 -> (1, "banana") -> index = 1, fruit = "banana"
step 3 -> (2, "mango") -> index = 2, fruit = "mango"Starting the Count at 1
People count from 1, so use start=1 for anything a human will read:
toppers = ["Asha", "Ravi", "Meena"]
for rank, name in enumerate(toppers, start=1):
print(f"Rank {rank}: {name}")Output:
Rank 1: Asha
Rank 2: Ravi
Rank 3: Meenastart only changes the number that is shown. It does not skip any items. toppers[1] is still "Ravi", not "Asha".
enumerate() Works on Any Iterable
for position, letter in enumerate("CODE"):
print(position, letter)Output:
0 C
1 O
2 D
3 EExample: Find Every Position of a Value
The list method index() only gives the first position. enumerate() makes it easy to find all of them:
marks = [78, 91, 65, 91, 88]
target = 91
positions = []
for i, m in enumerate(marks):
if m == target:
positions.append(i)
print(positions)Output:
[1, 3]Example: Change Items in Place
Assigning to the loop variable (like price = price - 10) only changes that variable, not the list. To update the list itself, you need the index. enumerate() gives you both:
prices = [100, 250, 80]
for i, price in enumerate(prices):
if price > 90:
prices[i] = price - 10 # Rs. 10 discount on items above Rs. 90
print(prices)Output:
[90, 240, 80]Example: Index of the Largest Value
scores = [45, 82, 67, 82, 30]
best_index = 0
for i, s in enumerate(scores):
if s > scores[best_index]:
best_index = i
print("Highest score", scores[best_index], "at index", best_index)Output:
Highest score 82 at index 1Because we used > and not >=, the first occurrence of the maximum wins. That's a detail interviewers like to ask about.
Part 2: zip()
zip(a, b, ...)takes two or more iterables and joins them item by item. The first step gives the first item of each, the second step gives the second item of each, and so on.
The name comes from a zipper, which joins two sides tooth by tooth:
names: "Asha" "Ravi" "Meena"
| | |
marks: 91 85 78
| | |
zip: ("Asha",91) ("Ravi",85) ("Meena",78)names = ["Asha", "Ravi", "Meena"]
marks = [91, 85, 78]
for name, mark in zip(names, marks):
print(name, "scored", mark)Output:
Asha scored 91
Ravi scored 85
Meena scored 78No indexes, no range(len()). And just like enumerate(), you can look inside with list():
names = ["Asha", "Ravi", "Meena"]
marks = [91, 85, 78]
print(list(zip(names, marks)))Output:
[('Asha', 91), ('Ravi', 85), ('Meena', 78)]Zipping Three or More Lists
names = ["Asha", "Ravi", "Meena"]
maths = [91, 85, 78]
physics = [88, 79, 92]
for name, m, p in zip(names, maths, physics):
print(name, "total:", m + p)Output:
Asha total: 179
Ravi total: 164
Meena total: 170With n lists, each step gives you n values, so you need n variables in the for line.
Example: Adding Two Lists Element by Element
Using + on two lists joins them. To add matching items instead, use zip():
a = [1, 2, 3]
b = [10, 20, 30]
result = []
for x, y in zip(a, b):
result.append(x + y)
print(a + b)
print(result)Output:
[1, 2, 3, 10, 20, 30]
[11, 22, 33]Example: Comparing Neighbours
Zipping a list with a slice of itself gives you every pair of neighbouring items. This is a neat trick for checking whether a list is sorted, or for finding day-to-day changes:
prices = [100, 104, 101, 110]
print(list(zip(prices, prices[1:])))
for today, tomorrow in zip(prices, prices[1:]):
print(today, "->", tomorrow, "change:", tomorrow - today)Output:
[(100, 104), (104, 101), (101, 110)]
100 -> 104 change: 4
104 -> 101 change: -3
101 -> 110 change: 9prices[1:] is the list shifted by one, so item i is paired with item i + 1. A list of 4 prices gives 3 pairs.
When the Lists Have Different Lengths
By default, zip() stops at the shortest iterable. Extra items in longer ones are silently ignored:
roll_numbers = [1, 2, 3, 4]
names = ["Asha", "Ravi"]
print(list(zip(roll_numbers, names)))Output:
[(1, 'Asha'), (2, 'Ravi')]Roll numbers 3 and 4 just disappeared, with no warning. That's convenient sometimes, but it can hide bugs. You have two other options.
Option 1: strict=True (Python 3.10+)
If the lengths should always be equal, ask zip() to check for you:
roll_numbers = [1, 2, 3, 4]
names = ["Asha", "Ravi"]
print(list(zip(roll_numbers, names, strict=True)))Output:
ValueError: zip() argument 2 is shorter than argument 1Now the mistake is caught immediately instead of producing quietly wrong results.
Option 2: zip_longest() to Keep Everything
If you want to go until the longest list ends, use zip_longest() from the itertools module. Missing values are filled with None, or with a fillvalue you choose:
from itertools import zip_longest
roll_numbers = [1, 2, 3, 4]
names = ["Asha", "Ravi"]
print(list(zip_longest(roll_numbers, names)))
print(list(zip_longest(roll_numbers, names, fillvalue="Absent")))Output:
[(1, 'Asha'), (2, 'Ravi'), (3, None), (4, None)]
[(1, 'Asha'), (2, 'Ravi'), (3, 'Absent'), (4, 'Absent')]Tool | Different lengths | Use when |
|---|---|---|
| Stops at the shortest | Extra items can safely be ignored |
| Raises | Lengths must match; a mismatch means a bug |
| Goes to the longest, fills gaps | You must not lose any item |
Unzipping with zip(*pairs)
zip() can also work in reverse. If you have a list of pairs, you can split it back into separate groups:
pairs = [("Asha", 91), ("Ravi", 85), ("Meena", 78)]
names, marks = zip(*pairs)
print(names)
print(marks)Output:
('Asha', 'Ravi', 'Meena')
(91, 85, 78)The * spreads the list out into separate arguments, so zip(*pairs) is the same as writing:
zip(("Asha", 91), ("Ravi", 85), ("Meena", 78))Now zip() takes the first item of each pair (all the names) and then the second item of each pair (all the marks). The results come out as tuples. Wrap them in list() if you need lists.
Once you learn dictionaries, a related trick is dict(zip(keys, values)), which builds a dictionary from two lists in one line.
Using enumerate() and zip() Together
Now we can write the loop from the start of the chapter:
names = ["Asha", "Ravi", "Meena"]
marks = [91, 85, 78]
for rank, (name, mark) in enumerate(zip(names, marks), start=1):
print(rank, name, mark)Output:
1 Asha 91
2 Ravi 85
3 Meena 78Read it from the inside out:
zip(names, marks) -> ("Asha", 91), ("Ravi", 85), ...
enumerate(..., start=1) -> (1, ("Asha", 91)), (2, ("Ravi", 85)), ...
rank, (name, mark) -> rank = 1, name = "Asha", mark = 91The brackets in (name, mark) are required. Each item from enumerate() has two parts: the counter and the inner pair. Without the brackets, Python would try to unpack the outer pair into three variables and fail.
They Are Lazy and Single-Use
enumerate() and zip() don't build a list. They return special objects that produce the next pair only when the loop asks for it. That's why printing them directly doesn't show the pairs:
names = ["Asha", "Ravi"]
marks = [91, 85]
print(zip(names, marks))Output (the address will be different on your computer):
<zip object at 0x000002AEF056F000>These objects can be used only once. After you've gone through them, they're empty:
names = ["Asha", "Ravi"]
marks = [91, 85]
pairs = zip(names, marks)
print(list(pairs))
print(list(pairs))Output:
[('Asha', 91), ('Ravi', 85)]
[]If you need the pairs more than once, save them as a list: pairs = list(zip(names, marks)). You'll learn exactly why this happens in the Iterators & Generators chapter.
Time and Space Complexity
Operation | Time | Extra space |
|---|---|---|
Creating | O(1) | O(1) |
Getting each next pair | O(1) | O(1) |
Looping over | O(n) | O(1) |
Looping over | O(min(len(a), len(b))) | O(1) |
| O(n) | O(n), a new list of pairs |
Because nothing is copied, using enumerate() or zip() in a loop costs no extra memory. The neighbour trick zip(prices, prices[1:]) is the exception: the slice prices[1:] creates a copy, so it uses O(n) extra space.
Choosing the Right Tool
You need | Use |
|---|---|
Only the items |
|
Index and item |
|
A human-friendly count |
|
Matching items from two or more lists |
|
Index plus items from several lists |
|
Only the index (e.g. swapping items) |
|
A Practical Example: Report Card
subjects = ["Maths", "Physics", "Chemistry", "English"]
marks = [92, 78, 85, 69]
max_marks = [100, 100, 100, 75]
total = 0
total_max = 0
for no, (subject, got, out_of) in enumerate(zip(subjects, marks, max_marks, strict=True), start=1):
percent = got / out_of * 100
print(f"{no}. {subject:<10} {got}/{out_of} ({percent:.1f}%)")
total += got
total_max += out_of
print(f"Overall: {total}/{total_max} = {total / total_max * 100:.2f}%")Output:
1. Maths 92/100 (92.0%)
2. Physics 78/100 (78.0%)
3. Chemistry 85/100 (85.0%)
4. English 69/75 (92.0%)
Overall: 324/375 = 86.40%zip() keeps each subject lined up with its marks, strict=True protects us if someone forgets to add a mark, and enumerate(..., start=1) numbers the lines. {subject:<10} pads the subject name to 10 characters so the columns line up, as you saw in the f-strings chapter.
Common Mistakes
1. Forgetting enumerate()
names = ["Asha", "Ravi", "Meena"]
for i, name in names:
print(i, name)Output:
ValueError: too many values to unpack (expected 2)Without enumerate(), each item is a string like "Asha", and Python tries to unpack its 4 letters into 2 variables. Worse, if every string happened to have exactly 2 letters, like ["Al", "Bo"], there would be no error: i would be "A" and name would be "l". Always write enumerate(names).
2. Expecting start=1 to Change the Indexes
enumerate(lst, start=1) gives counters 1, 2, 3, ... but the first item is still at lst[0]. If you use that counter as an index, as in lst[i], you'll be off by one, and the last step raises IndexError.
3. Silent Truncation with zip()
If one list is shorter, items are dropped without warning. Use strict=True when the lengths must match.
4. Reusing a zip or enumerate Object
The second loop over the same object does nothing because it's already used up. Create it again, or store it with list().
5. Missing Brackets When Combining
for i, name, mark in enumerate(zip(names, marks)): fails with ValueError: not enough values to unpack (expected 3, got 2). Write for i, (name, mark) in ....
Interview Tips
"How do you get the index while looping in Python?" Use
enumerate(), notrange(len()). Mention thestartparameter."How do you loop over two lists at the same time?"
zip(). Then mention what happens with different lengths: it stops at the shortest,strict=True(Python 3.10+) raises an error, anditertools.zip_longest()fills the gaps."How do you unzip a list of pairs?"
zip(*pairs)."What does
zip()return?" A lazy zip object (an iterator), not a list. It produces tuples one at a time and can be used only once."How do you check if a list is sorted?" Compare neighbours with
zip(lst, lst[1:])and check that everya <= b.
Summary
enumerate(iterable, start=0)gives(counter, item)pairs. Use it when you need the position and the item.zip(a, b, ...)gives tuples of matching items from each iterable. Use it to walk through related lists together.zip()stops at the shortest input. Usestrict=Trueto catch length mismatches, orzip_longest()to keep everything.zip(*pairs)unzips a list of pairs.Both are lazy and single-use, and cost O(1) extra memory in a loop.
Combine them as
for i, (a, b) in enumerate(zip(x, y)):.
Need the position?
enumerate(). Need lists side by side?zip(). Need both? Use them together.
You've seen pairs like (0, 'apple') all through this chapter. In the next chapter, we'll study these tuples properly.