Skip to the solution
MediumDSA11 min read

How does a for loop work under the hood?

725 views

The problem

Question presented to candidate: "Forget the syntax for a second. When Python runs for x in something:, what actually happens, step by step? What does the interpreter call, how does it know when to stop, and what does that explain about bugs like modifying a list while you loop over it?"

What a strong answer should cover:

  • The loop calls iter(something) once (which uses type(something).__iter__, or the __getitem__ fallback), then calls next() on the result before every pass, assigning the value to the loop target
  • The loop ends when __next__ raises StopIteration; the loop catches it, so the user never sees it, and then the else clause runs if there was no break
  • It is equivalent to a while True loop with try: x = next(it) except StopIteration: break; CPython compiles it to GET_ITER plus a FOR_ITER / JUMP_BACKWARD loop (END_FOR added in 3.12)
  • The loop target is an ordinary assignment: it can unpack, it keeps its last value after the loop, and rebinding it in the body does not affect the next item
  • Consequences: a list iterator is just an index, so removing items while looping skips elements; dicts and sets raise RuntimeError if their size changes; a generator can only be looped once
  • for works on any iterable, not only sequences: no indexes are involved, which is why it works on files, generators and infinite streams

Code / implementation expected: Optional β€” rewriting a for loop as the equivalent while loop with iter(), next() and StopIteration.

  • iteration
  • for-loop

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonEvery protocol call a for loop makes, and the while-loop it equals
PythonThe bytecode, mutating while looping, dicts, generators and range

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 71 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do you create and chain custom exceptions?

Continue