Skip to content

Files

Latest commit

 

History

History

Iterators

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Iterators

Iterator protocol

  • 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)
  1. for x in foo will actually call iter(foo)
  2. iter built in function calls
foo.__iter__ 
  1. The __iter __ method must return an iterator object.
  2. Iterator objects theirselves implement the __next __ special method.
  3. Then for_loop repeatedly calls next built-in function on iterator object until its exhausted.
  4. Once iterator is exhausted it raises StopIteration exception.