ProgrammingModerateTCS NQT · Infosys pattern

What is printed?

What is printed?
i = 10
squares = [i * i for i in range(3)]
for j in range(3):
    pass
print(i, squares, j)
  1. A. 10 [0, 1, 4] 2
  2. B. 2 [0, 1, 4] 2
  3. C. 10 [0, 1, 4] 3
  4. D. 10 [0, 1, 4] NameError

Correct answer: A. 10 [0, 1, 4] 2

A list comprehension has its own scope in Python 3, so its i does not overwrite the outer i (still 10). A for loop variable does leak: j keeps its last value 2 after the loop.

More Python Programming questions

Exams that ask this topic