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)
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:An iterator is a more generic class, which gives you more flexibility (example maintaining state, restarting generator), which is however more verbose: