Skip to content
Tech News
← Back to articles

What `for x in y` hides from you – From Scratch Code

read original more articles

What a Python `for` loop is really doing once you stop hand-waving.

There are certain Python features that are so straightforward to use, you forget they are doing anything at all.

Consider for x in y .

You write a list, or a string, or a range, and Python politely hands you back one item at a time. No index variable and no bounds checks. Compared to i++ from C/C++ or forEach from JavaScript, Python's version just works.

For a long time, I treated for x in y as just a syntax that meant “loop over this thing,” and that was enough. Then I started building Memphis, my Python interpreter in Rust, and eventually I had to stop hand-waving and answer an extremely rude question:

What is a for loop actually doing?

It turns out the answer is both simpler and more involved than I expected.

The illusion

Let’s start with a tiny example.

for x in [10, 20, 30]: print(x)

... continue reading