Advanced · 13 min
Generators
Produce values lazily with yield and consume them as needed.
Yield one value at a time
A generator pauses at yield and resumes on the next request. It avoids building the whole result list first.
def countdown(start):
while start > 0:
yield start
start -= 1
print(list(countdown(3)))Output
[3, 2, 1]
Build a pipeline
Generator expressions are lazy. Functions such as sum() can consume their values directly.
numbers = [2, 3, 4]
squares = (number ** 2 for number in numbers)
print(sum(squares))Output
29
Generators
- Read both generators examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Generate even numbers
Complete evens(limit) so it yields the even numbers from 0 through limit. Display the supplied list.
Loop through range(limit + 1) and yield values divisible by two.