What are generators in Python?

Generators in Python.

Generator functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

A generator is a simple way to create a lazy sequence of values.

A generator function looks lot like a normal function, but it uses a yield statement where you might normally use a return statement. For example:

def powers(max):

x = 1
while x < max:
yield x
x *= 2

If this was a function, you would expect the loop to start with x equal to 1, and then double x each time through the loop until x reaches max. But the yield statement causes Python to treat this as a generator rather than a normal function. Each time yield is called, it returns a value, but the next time the generator is invoked, it carries on from where it left off. So it returns values of 1, 2, 4, 8 etc.

You can use a generator in a for loop, in place of a range function. For example

for i in powers(64):

will print 1, 2, 4, 8, 16, 32. It stops at 64 because that is the max value supplied to the generator function.