Iterators

An iterator is an object that implements the method __iter__. Iterators also implement __next__ which returns the next element of the iterator, until a StopIteration exception is raised.

class FibonacciIter:
    previous = 0
    current = 1
    index = 0
    
    def __init__(self, count):
        self.count = count
        
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index >= self.count:
            raise StopIteration
        
        current = self.current + self.previous
        self.previous = self.current
        self.current = current
        self.index += 1
        return current

for n in FibonacciIter(10):
    print(n)

Iterators are what allow us to loop over things in python. Everytime you use a loop, behind the scenes python calls it __iter__ method.

You may not use iterators much, but many packages you use do. So it’s important to know how they function.