yield
- Python course
- Intermediate
- Lesson 100/116
- 5 min
Learn generator functions with yield.
yield
The yield keyword turns a function into a generator. Unlike return, after producing a value the function does not end; it pauses and continues from where it left off on the next call.
Example: def count_up():\n yield 1\n yield 2\n yield 3. The call for v in count_up(): produces 1, 2, 3 in order. Each yield gives a value and the function pauses. Generators are ideal for producing large data lazily; the whole list is not loaded into memory.
Lazy production
Generators work lazily: a value is not produced until requested. The next(g) call advances to the next yield. The for loop does this automatically.
This property is useful for infinite sequences or very large data. Example: def fib():\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a + b. This generator never ends; but you can safely take the first 10 terms with islice(fib(), 10).
Practice Write the count_up generator
Define the function def count_up():. In the body include yield 1, yield 2 and yield 3. Then loop with for v in count_up(): and print each value with print(v).
Starter code
# Write the count_up generator and print valuesSample solution
# Write the count_up generator and print values
def count_up():
yield 1
yield 2
yield 3
for v in count_up():
print(v)Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does yield differ from return?
- It runs faster
- It does not end the function, it pauses Correct answer
- It only returns numbers
- It is used inside classes
Explanation: yield produces a value and pauses.
2 Complete the yield line
def count_up():
____ 1
yield 2
yield 3
def count_up():
yield 1
yield 2
yield 3
Explanation: yield 1 produces the value and pauses.
3 Match the yield parts
| Term | Meaning |
|---|---|
yield |
Produce value |
next(g) |
Next value |
for v in g |
Auto iteration |
pause |
Pause |