ProgrammingVery hardPython · GATE DA · Advanced

What is printed?

What is printed?
x = 10
class K:
    x = 20
    ys = [x + i for i in range(2)]
print(K.ys)
  1. A. NameError
  2. B. [10, 11]
  3. C. [20, 21]
  4. D. [0, 1]

Correct answer: B. [10, 11]

In a class body the first iterable of a comprehension is evaluated in the class scope, but the expression x + i runs in the comprehension's own function scope, which skips the class namespace and finds the global x = 10.

More Python Programming questions

Exams that ask this topic