Article URL: https://fromscratchcode.com/blog/what-for-x-in-y-hides-from-you/ Comments URL: https://news.ycombinator.com/item?id=48920156 Points: 12 # Comments: 13

There are certain Python features that are so straightforward to use, you forget they are doing anything at all. 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: If you’re starting out with Python, it’s easy to come away with a mental model like this: Python is not looping over the collection directly. It is looping over an iterator. That distinction matters because it explains why for works on so many different kinds of objects, and why iteration in Python feels so flexible. Once this clicked for me, a bunch of Python behavior stopped feeling mysterious. Run that second snippet too. The last next(it) raises StopIteration, which is exactly how the loop knows it is done.