Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. return vs yield

Python · Functions & Decorators

return vs yield

Mediumpython-16
returnyieldgeneratorfunctions

Question

What is the difference between return and yield?

Solution

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 yielded

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

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext