I have a program below that I tried to understand the difference between an iterator and a generator.I get that a generator is an iterator and more
.
I appreciate the generators are short and succinct way to generate iterators.
But other than brevity is there some other feature that generators provide that iterators doesn't
def squares(start, stop):
for i in range(start, stop):
yield i * i
generator = squares(1, 10)
print(list(generator))
class Squares(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
iterator = Squares(1, 10)
l = [next(iterator) for _ in range(1,10)]
print(l)