Iterator is any object with __iter__ and __next__. Generator is a special iterator created with yield.
1# Iterator — any object with __iter__ and __next__2class CountUp:3 def __init__(self, stop):4 self.stop = stop5 self.current = 067 def __iter__(self):8 return self910 def __next__(self):11 if self.current >= self.stop:12 raise StopIteration13 self.current += 114 return self.current1516# Generator — simpler, uses yield17def count_up(stop):18 current = 019 while current < stop:20 current += 121 yield current2223# Both work the same way24for n in CountUp(5):25 print(n) # 1, 2, 3, 4, 52627for n in count_up(5):28 print(n) # 1, 2, 3, 4, 5
Advantages of generators:
send(), throw(), close().