Editor

Your First Generator

Intermediate · Write the code · from Python Generators: Process Millions of Items Without Running Out of Memory

From the lesson: How Do You Create and Use a Generator?

Notice that "Starting countdown!" doesn't print until the first next() call. The function body is completely frozen until you ask for a value. After yielding 1, the next next() call would print "Blastoff!" and then raise StopIteration.

Read this part of the lesson

Write a generator function called evens_up_to(n) that yields all even numbers from 2 up to and including n.

for e in evens_up_to(10):
    print(e)
# Output: 2 4 6 8 10
def evens_up_to(n):
# Yield even numbers from 2 to n (inclusive)
pass
for e in evens_up_to(10):
print(e)

More Generator exercises

All Python exercises · 50 practice problems · Advanced Python quiz