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)
The two examples that you've posted are equivalent.
The main advantages that generators offer over iterators (that aren't generators) is that generators use less memory, can be faster, and can be used on infinite streams.
When you use an iterator, all the items that are going to be returned eventually are calculated, then the first the element is returned.
With a generator the first element is returned before the second item is calculated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.