Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How does a for loop work under the hood in Python?

SHORT ANSWER

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

python
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: c

Both 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.

#python#iterators

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.