Comprehensions & Generators · Question 20 · Hard
The name arr is rebound to a new list after a generator expression is created but before it is consumed. What does list(g) give?
arr = [1, 2, 3]
g = (x for x in arr if arr.count(x) > 0)
arr = [2, 4]
print(list(g))
- [1, 2, 3]
- [2]
- [2, 4]
- []
Answer and explanation
Answer: B. [2]
Explanation: The iterable of the first for clause is evaluated immediately, so the generator loops over the old list [1, 2, 3]. The condition runs lazily and looks up arr later, when it is [2, 4], so only 2 passes.
Previous: 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 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?
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