-
Iterator protocol is how python for loops and related expressions traverse the contents of a container type.
-
what happens when Python sees an expression like
foo = [1,2,3]
for x in foo: # what is happening in this exact statement
print(x)
- for x in foo will actually call iter(foo)
- iter built in function calls
foo.__iter__
- The __iter __ method must return an iterator object.
- Iterator objects theirselves implement the __next __ special method.
- Then for_loop repeatedly calls next built-in function on iterator object until its exhausted.
- Once iterator is exhausted it raises StopIteration exception.