How does a for loop work under the hood in Python?
A for loop calls iter() on the object to get an iterator, then repeatedly calls next() on it, running the body each time. When next() raises StopIteration, the loop ends quietly.
Explain it simply
A for loop is a polite version of a conductor repeating "next seat please" until there are no seats left. You never see the conductor or the "no more seats" signal, because the loop handles both for you.
Example
items = ["a", "b", "c"]
for x in items:
print(x)
# Output: a
# Output: b
# Output: c
it = iter(items)
while True:
try:
x = next(it)
except StopIteration:
break
print(x)
# Output: a
# Output: b
# Output: cBoth halves do the same job. The second one is exactly what Python does internally for the first.
Because the protocol is so simple, anything that has __iter__ can be used in a for loop, including your own classes, files, dictionaries and generators.
What to say in the interview
"for calls iter() on the iterable, then next() until StopIteration, which it catches and uses to end the loop. That's why any object supporting the iterator protocol, not just built-in collections, works in for loops, comprehensions, unpacking and functions like sum and list."
Common mistakes
- Modifying a list while looping over it, which changes the position the iterator is tracking.