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)
  1. 2 [0, 1, 4]
  2. 10 [100, 100, 100]
  3. 10 [0, 1, 4]
  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

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