Predict the Generator Output
Intermediate · Predict the output · from Python Generators: Process Millions of Items Without Running Out of Memory
From the lesson: What Are Generator Expressions?
Just like list comprehensions create lists, generator expressions create generators. The syntax is identical - just swap the square brackets for parentheses.
Read this part of the lessonWhat will this code print? Think carefully - generator expressions are lazy.
def make_gen():
return (x * 10 for x in range(4))
g = make_gen()
next(g)
print(next(g))
print(sum(g))Write two print() statements that produce the exact same output.
# Predict the output and write the matching print statements
print("?")
print("?")
More Generator exercises
- Your First GeneratorIntermediate
- Refactor to a GeneratorIntermediate
- Flatten with yield fromAdvanced
- Build a Data PipelineAdvanced
- Fix the Generator BugAdvanced
- Infinite Fibonacci GeneratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz