About Lesson
What is Generators in Python
Generator functions act just like regular functions with just one difference that they use the Python yield keyword instead of return. A generator function is a function that returns an iterator. A generator expression is an expression that returns an iterator. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop.
Example
def test_sequence(): num = 0 while num < 10: yield num num += 1 for i in test_sequence(): print(i, end=", ") Output 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
A return statement terminates a function entirely but a yield statement pauses the function saving all its states and later continues from there on successive calls.