defcountdown(n:int):while n >0:yield n
n -=1for tick incountdown(3):print(tick)# Generators are lazy - values produced one at a time
nums =countdown(1_000_000)print(next(nums))
Output
3
2
1
1000000
Note Generators produce values lazily, consuming almost no memory regardless of size. They are single-use: once exhausted, they cannot be restarted.
defflatten(nested):for item in nested:ifisinstance(item,list):yieldfromflatten(item)else:yield item
data =[1,[2,[3,4]],[5,6]]print(list(flatten(data)))
Output
[1, 2, 3, 4, 5, 6]
Note yield from delegates to a sub-generator and passes values through. It handles send() and throw() transparently, unlike a manual for-loop with yield.
Note Generators are lazy -- they produce values on demand. Execution pauses at each yield and resumes when next() is called.
Frequently asked questions
How does Python handle yield?
This task is covered in 2 stacks on this page: Python, JavaScript. The "Generators with yield" snippet in Python uses `def gen():`.
Which code does the Python example use?
The "Generators with yield" snippet uses `def gen():`, from the Functions section of the Python cheat sheet.
Which stacks cover "yield" on this page?
Python, JavaScript. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Generators with yield": Generators produce values lazily, consuming almost no memory regardless of size. They are single-use: once exhausted, they cannot be restarted.