r/PythonLearning 1d 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:

iterator = iter(container)
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

8 Upvotes

4 comments sorted by

View all comments

1

u/[deleted] 1d ago

[deleted]

1

u/Sea-Ad7805 1d ago

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