What `for x in y` hides from you – From Scratch Code
3 hours ago
- #Iteration
- #Programming Concepts
- #Python
- A Python 'for x in y' loop actually works by using an iterator protocol: it first calls iter(...) to get an iterator, then repeatedly calls next(...) to get values, and stops when StopIteration is raised.
- The for loop syntax is a wrapper that hides the underlying mechanism, which is the same for all iterable objects like lists, strings, ranges, and generators, making iteration feel unified and flexible.
- Understanding this reveals that iteration is not directly over the collection but over an iterator, which can be exhausted (like in the example where a second loop prints nothing after the first uses up the iterator).
- This design allows custom objects to participate in iteration by implementing __iter__() and __next__(), and explains why unpacking in loops (e.g., 'for x, y in pairs') works without special logic.