Iterators:
IteratorIterators are objects which usesuse the next() method to get next valuethe following values of a sequence.
Generators:
A generator is a functionGenerators are functions that producesproduce or yieldsyield a sequence of values using the yield methodkeyword.
Every next() method call on a generator object(for ex: f as in below example) returned by a generator function (for ex: foo() function in below example), generates the next value in the sequence.
When a generator function is called, it returns an generator object without even beginning the execution of the function. When the next() method is called for the first time, the function starts executing until it reaches yielda yield statement which returns the yielded value. The yieldyield keeps track of what has happened, i.e. it remembers the last execution. And secondsecondly, the next() call continues from the previous value.
The following example demonstrates the interplay between yieldyield and the call to nextthe next method on a generator object.
>>> def foo(): ... print ("begin") ... for i in range(3): ... print ("before yield", i) ... yield i ... print ("after yield", i) ... print ("end") ... >>> f = foo() >>> f.next(f) begin before yield 0 # Control is in for loop 0 >>> f.next(f) after yield 0 before yield 1 # Continue for loop 1 >>> f.next(f) after yield 1 before yield 2 2 >>> f.next(f) after yield 2 end Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>