Thursday, September 27, 2018

What is the difference between an Iterator and a Generator?



What is the difference between an Iterator and a Generator?


Answer



Generators are iterators, but not all iterators are generators.




An iterator is typically something that has a next method to get the next element from a stream. A generator is an iterator that is tied to a function.



For example a generator in python:



def genCountingNumbers():
n = 0
while True:
yield n
n = n + 1



This has the advantage that you don't need to store infinite numbers in memory to iterate over them.



You'd use this as you would any iterator:



for i in genCountingNumbers():
print i
if i > 20: break # Avoid infinite loop



You could also iterate over an array:



for i in ['a', 'b', 'c']:
print i

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...