return ends a function and hands back one value (or None). yield pauses a generator function and hands back one value in a stream; the function can continue later.
| | return | yield | | --- | --- | --- | | Ends the call? | Yes | No (pauses) | | How many values? | One final result | Many over time | | Caller gets | The value | A generator object first | | Memory | Eager if you build a list | Lazy by default |
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 yieldedIf you need all results at once for random access, return a list. If you need streaming or large/infinite sequences, yield.