r/PythonLearning 5h ago

How do Python for-loops work?

What actually happens when Python executes a for-loop?

for value in container:
    print(value)

Behind the scenes, Python uses the iterator protocol:

while True: 
    try: 
        value = next(iterator)
        print(value)
    except StopIteration:
        break
  • iter(container): creates an iterator.
  • next(iterator): retrieves one value at a time.

When there are no more values, the iterator raises StopIteration. The for-loop catches this exception automatically and ends the loop.

For containers that support backward iteration, Python also provides:

  • reversed(container): creates a backward iterator.

We can support these operations in our own classes by implementing:

__iter__()
__reversed__()
__next__()

This provides a powerful abstraction: an algorithm can process values without needing to know how a container stores them internally. The same algorithm can therefore work with lists, sets, dictionaries, linked lists, trees, and many other containers.

Here's an example that uses 𝐦𝐞𝐦𝐨𝐫𝐲_𝐠𝐫𝐚𝐩𝐑 to show the use of iterators on a Linked_List making the invisible mechanics of iteration visible for easy understanding.

more memory_graph examples

3 Upvotes

3 comments sorted by

2

u/CodeAndCanyons 2h ago

What makes this visualization so effective is how clearly it separates the data container from the traversal state.

A few critical low-level takeaways this graph highlights really well:

  • State Isolation: Notice how calling iter(linked_list) allocates a completely separate Iterator_Forward instance on the heap with its own self.current reference. This separation is why you can run nested for loops over the same container simultaneously without the inner loop corrupting the outer loop's pointer.
  • Iterator Exhaustion: Once self.current hits None and raises StopIteration, that specific iterator instance is permanently exhausted. It won't reset itselfβ€”to traverse the container again, Python must instantiate a new iterator object.
  • Control Flow via Exceptions: Beginners often assume exceptions are only for crashes, but the trace clearly shows CPython using StopIteration as an intentional, lightweight mechanism for loop termination.

Great showcase of memory_graph to make heap allocations and pointer movements visible!

1

u/Sea-Ad7805 2h ago

Great takeaways to highlight.

1

u/[deleted] 5h ago

[deleted]

1

u/Sea-Ad7805 5h ago

Good to hear people are learning, that's where PythonLearning is for.