Write a Python generator function and show that it produces values lazily.
A generator is a function that produces its values one at a time, when they are asked for, instead of building the whole collection first. You write a generator with the yield keyword in place of return.
def counter(limit):
for number in range(limit):
yield number * 10
gen = counter(4)
print('type:', type(gen).__name__)
print('first:', next(gen))
print('second:', next(gen))
print('rest:', list(gen))
Calling counter(4) does not run the body of the function at all. It gives you back a generator object, and the body only starts when you ask for the first value. Each call to next() runs the body up to the next yield, produces one value, and pauses the function at that exact spot while keeping its local variables alive.
The last line shows the lazy behaviour clearly. list(gen) produced only the two values that had not been handed over yet, because the first two had already been given away. Once a generator runs out of values, calling next() on it again raises StopIteration, and list() on it gives you an empty list.
Two details are worth remembering. The generator remembers where it was, so resuming it continues after the yield instead of starting the function again. And the local variables of the suspended function are kept safe, which is what makes a generator useful for looping over data that is still being produced.
A quick way to see the memory difference is to compare sys.getsizeof() on a list of a million values with the same values produced by a generator expression. The list takes tens of megabytes, and the generator object takes a couple of hundred bytes. The sys module is part of the standard library, so you can import it in any Python program.