Python · Functions & Decorators

return vs yield

Mediumreturnyieldgeneratorfunctions

Interview question

What is the difference between return and yield?

How to answer

The short answer

return ends a function and hands back one value (or None). yield pauses a function and hands back one value in a stream; the function can continue later.

returnyield
Ends the call?YesNo (pauses)
How many values?One final resultMany over time
Caller getsThe valueA generator object first
MemoryEager if you build a listLazy by default
Python
def eager_squares(n):
    out = []
    for i in range(n):
        out.append(i * i)
    return out            # full list now

def lazy_squares(n):
    for i in range(n):
        yield i * i       # one at a time

print(eager_squares(3))          # [0, 1, 4]
print(lazy_squares(3))           # <generator object ...>
print(list(lazy_squares(3)))     # [0, 1, 4]

def maybe():
    yield 1
    return "done"   # becomes StopIteration.value; not yielded

If you need all results at once for random access, return a list. If you need streaming or large/infinite sequences, yield.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill