dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Generators vs Iterators #60

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

TL;DR: All generators are iterators, but not all iterators are generators

A python generator is a special case of an iterator. A generator can be any function that includes the yield statement:

def squares(start, stop):
    for i in range(start, stop):
        yield i * i

generator = squares(a, b)

An iterator is a more generic class, which gives you more flexibility (example maintaining state, restarting generator), which is however more verbose:

class Squares(object):
    def __init__(self, start, stop):
       self.start = start
       self.stop = stop
    def __iter__(self): return self
    def next(self): # __next__ in Python 3
       if self.start >= self.stop:
           raise StopIteration
       current = self.start * self.start
       self.start += 1
       return current # can also be "yield"

iterator = Squares(a, b)
dvas0004 commented 5 years ago

https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators