Lesson 04
Python Generators and yield — Values On Demand
Learn Python generators with YouTube autoplay: yield pauses, return finishes, next() resumes, kvrange patterns, and StopIteration when empty.
:
yield "PYTHON"
yield "HTML"
yield "C"
yield "C++"
g = getcourses() print(next(g)) # PYTHON print(next(g)) # HTML
Every `next(g)` asks for **one more value**.
## What you will learn
- A **generator** is a function that contains **`yield`**
- **`return`** finishes the function; **`yield`** pauses and can continue
- Generator objects: pull with `next()` or `for`; extra `next()` → **`StopIteration`**
- Four `yield`s vs four `return`s — generator vs normal function
- **`kvrange`**: three ways to drain a generator
## `return` vs `yield`

```python
def getcourses():
return "PYTHON"
return "HTML"
return "C"
return "C++"
nitcrs = getcourses()
print(nitcrs, type(nitcrs)) # PYTHON <class 'str'>Only the first return runs. Later lines are dead code.
How yield pauses
Think of climbing stairs. Every landing is a yield point.
:
yield "PYTHON" # pause here
yield "HTML" # pause again
yield "C"
yield "C++"The function does not restart. It resumes exactly after the previous yield.
Several yields
def getcourses():
yield "PYTHON"
yield "HTML"
yield "C"
yield "C++"
nitcrs = getcourses()
print("Type of nitcrs=", type(nitcrs)) # <class 'generator'>
print(next(nitcrs))
print(next(nitcrs))
print(next(nitcrs))
print(next(nitcrs))
# next(nitcrs) # StopIterationRun the full script in the playground below.
What does a generator return?
A generator function does not return a string or list. It returns a generator object.

print(type(g))
# <class 'generator'>The object waits quietly until someone calls next(g).
Three ways to use a generator
The kvrange() example shows three common patterns.
def kvrange(val):
i = 0
while i < val:
yield i
i += 1Method 1 — next() manually
print(next(r))
print(next(r))
print(next(r))
### Method 2 — `while` + `StopIteration`
)
except StopIteration:
breakMethod 3 — for loop (recommended)
:
print(value)
## Why generators save memory
Imagine a warehouse with one million boxes. You do not move everything home — you request **one box at a time**.
:
return [0, 1, 2, 3, 4]Generator — creates values only when needed:
def numbers():
yield 0
yield 1
yield 2Generators are ideal for large files and streaming data.
What happens after the last value?
Once every yield has been used, the generator is empty.

next(g)
next(g)
next(g)
next(g)
next(g) # StopIterationThis exception simply means: there are no more values left.
Real-world examples
is called.
Loading playground…
Check your understanding
Generators and yield quiz
A function with yield returns when called:
1 / 10