← Python lessons

Python yield vs return: Lazy Evaluation with Generators

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

In Python, yield vs return decides when the work happens. return finishes everything, then hands back one result. yield hands back one value and pauses, so work is done only when asked for. That is lazy evaluation.

You will watch the order of work change, and learn when each keyword fits. Prerequisites: Python Generator in a for Loop. No imports are needed. The print("loading", ...) lines are only there to show when the work happens.

return does all the work first

def load_all(names):    loaded = []    for name in names:        print("loading", name)        loaded.append(name.upper())    return loadedfor player in load_all(["ada", "bo", "cy"]):    print("showing", player)

All three loading lines print before the first showing line. The loop receives nothing until the whole list is built.

yield does the work on demand

def load_each(names):    for name in names:        print("loading", name)        yield name.upper()for player in load_each(["ada", "bo", "cy"]):    print("showing", player)

Now the lines alternate: loading ada, showing ADA, loading bo, and so on. Each value is made at the moment the loop asks for it. No list is built.

Lazy evaluation skips work you never ask for

If the caller stops early, the remaining work never happens.

def load_each(names):    for name in names:        print("loading", name)        yield name.upper()for player in load_each(["ada", "bo", "cy"]):    print("showing", player)    if player == "BO":        break

cy is never loaded. With load_all(), all three names would be loaded before the loop could stop.

When return is the better choice

A generator has no length and cannot be indexed. It can be read once, in order.

def load_each(names):    for name in names:        yield name.upper()players = load_each(["ada", "bo", "cy"])print(len(players))  # this line raises TypeError: a generator has no len()

Return a list when you need len(), an index such as players[0], or a second pass. Yield when the values are read once, when there are many of them, or when the caller may stop early.

Note: list(load_each(names)) turns a generator back into a list. It also does all the work at once.

See also: Python yield: Write a Generator Function, Parameters and return.

Your turn

Write the generator lengths(words). For each word it prints measuring and the word, then yields the word's length. The loop below it is supplied and stops early.

🎯 Goal — make it print exactly:
measuring kiwi
got 4
measuring banana
got 6
# Define lengths(words) here: print "measuring" and the word, then yield its length.for size in lengths(["kiwi", "banana", "fig", "cherry"]):    print("got", size)    if size > 4:        break