Comprehensions & Generators · Question 17 · Hard
A list comprehension uses a loop variable with the same name as a module-level variable. What does this code print?
x = 10
squares = [x * x for x in range(3)]
print(x, squares)
- 2 [0, 1, 4]
- 10 [100, 100, 100]
- 10 [0, 1, 4]
- 3 [0, 1, 4]
Answer and explanation
Answer: C. 10 [0, 1, 4]
Explanation: In Python 3 a comprehension has its own scope, so its loop variable x does not leak out or overwrite the outer x. The outer x is still 10 and the squares are of 0, 1 and 2.
Previous: The generator function below contains print calls around its yield. In what… · Next: The in operator is used twice on the same generator before it is turned into a…
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
- 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…
- The generator function below contains print calls around its yield. In what…
- 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