Comprehensions & Generators · Question 18 · Hard
The in operator is used twice on the same generator before it is turned into a list. What is printed?
g = (n for n in range(5))
print(3 in g, 2 in g, list(g))
- True False []
- True True []
- True False [4]
- True True [0, 1, 2, 3, 4]
Answer and explanation
Answer: A. True False []
Explanation: 3 in g pulls values 0, 1, 2, 3 and stops with True. 2 in g continues from 4, reaches the end without finding 2 and gives False. Nothing is left, so list(g) is empty.
Previous: A list comprehension uses a loop variable with the same name as a module-level… · Next: A nested list comprehension is applied to a 2 × 3 matrix. What does it produce?
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 dictionary comprehension swaps keys and values of a price list in which two…
- The generator function below contains print calls around its yield. In what…
- A list comprehension uses a loop variable with the same name as a module-level…
- 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