Python 101 : An introduction to Iterators and Iterables.


In pythoniterables are objects that we can loop through.

These objects implement an "__iter__()" function that returns an iterator.

The iterators objects have a "__next__()" function that returns the elements of the iterable object. They also have an "__iter__()" function that returns the "self" object. 

Python gets iterators from iterables.

Because strings in python are iterable, we can loop over them:


The above code is equivalent to:


An iterator class contains:
  • __next__() : returns the next element, it also raises a "StopIteration" when the end of the iterable object is reached.
  • __iter__() : returns "self", which is an iterator object.
There is an interface - collections.abc.Iterator - in python that implements these two functions as abstract methods - methods that has no instruction in it, serves only as template -.

Remark:

Iterator don't go backwards to start from the beginning of an iterable object, we get a new, fresh iterator.

Comments

Leave as a comment:

Archive