Editor

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 lesson

What 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

All Python exercises · 50 practice problems · Advanced Python quiz