Comprehensions & Generators · Question 16 · Hard
The generator function below contains print calls around its yield. In what order do the letters appear?
def numbers():
print("A")
yield 1
print("B")
g = numbers()
print("C")
next(g)
print("D")
- A C D
- A C B D
- C A B D
- C A D
Answer and explanation
Answer: D. C A D
Explanation: Calling numbers() only creates the generator; none of its body runs yet, so C is printed first. next(g) runs the body up to the yield, printing A, and B is never reached because the generator is not resumed again.
Previous: A dictionary comprehension swaps keys and values of a price list in which two… · Next: A list comprehension uses a loop variable with the same name as a module-level…
Practise comprehensions & generators
Try a fresh set of comprehensions & generators questions with an explanation after every answer, free and without signing up: Comprehensions & Generators practice. Or sit a full placement mock test.
More comprehensions & generators questions
- A comprehension walks through a list of rows and keeps only the odd values…
- Kavya has to add up one crore numbers read from a sensor. Why is sum(x for x…
- A dictionary comprehension swaps keys and values of a price list in which two…
- A list comprehension uses a loop variable with the same name as a module-level…
- The in operator is used twice on the same generator before it is turned into a…
- A nested list comprehension is applied to a 2 × 3 matrix. What does it produce?
- The name arr is rebound to a new list after a generator expression is created…
More python practice
Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge