bhylu.com

Advertisements

Python Generators

A generator yields values one at a time instead of creating the whole result at once. It is useful for a stream that can be processed incrementally.

Understand the idea

Calling a generator function returns an iterator; its body starts when values are requested. yield pauses execution and keeps local state until the next request. Once exhausted, it does not restart itself. A new call creates a new generator. This saves memory only when consumers also avoid collecting every value unnecessarily.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

def available_counts(counts):
    for count in counts:
        if count > 0:
            yield count

values = available_counts([0, 3, 1])
print(next(values))
print(list(values))

Read the result

The first result is 3, and collecting the remaining values gives [1]. The first value was already consumed.

Try one change

Call list on the generator a second time, then create a fresh generator and explain the difference.