This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Generators, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does yield do inside a generator function?
Answer: Pauses and produces a value
Why: yield hands one value to the caller and pauses the function.
What does the program output?
def gen():
yield 1
yield 2
print(list(gen()))Answer: [1, 2]
Why: list consumes both yielded values and builds a list.
What does calling a generator function return?
Answer: A generator object
Why: The body runs only when the generator is advanced.
What happens when next() reaches the end of a generator?
Answer: It raises StopIteration
Why: StopIteration signals that the generator has no more values.
Complete the keyword that yields one value.
def one():
____ 1
print(next(one()))Answer: yield
Why: yield produces a value and pauses the function.
Complete the built-in that pulls the next value.
def one():
yield 1
value = ____(one())
print(value)Answer: next
Why: next asks a generator for one more value.
Complete the function that turns a generator into a list.
def gen():
yield 1
print(____(gen()))Answer: list
Why: list consumes the generator and materializes its values.
Complete the function that consumes the squares.
print(____(n * n for n in range(4)))Answer: sum
Why: sum adds every value produced by the generator expression.
What appears on the screen?
print(list(n for n in range(3)))Answer: [0, 1, 2]
Why: The generator expression yields 0, 1, and 2, and list collects them.
What is printed?
def g():
yield "a"
print(next(g()))Answer: a
Why: next pulls the first yielded string, a.
What is the output?
def g():
yield 1
yield 2
x = g()
print(next(x), next(x))Answer: 1 2
Why: The two next calls return one and two, printed on the same line.
What does this code print?
def g():
for n in range(3):
yield n * 2
print(list(g()))Answer: [0, 2, 4]
Why: The generator yields 0, 2, and 4, and list shows them.
Try the questions first
Open the practice page for Python Generators and answer the same 12 questions with instant feedback.