ProgrammingVery hardProduct company OA

What is printed?

What is printed?
x = 1
class K:
    x = 2
    a = [x for _ in range(2)]
    b = [x * i for i in range(x + 1)]
    def m(self): return x
print(K.a, K.b, K().m(), K.x)
  1. A. [1, 1] [0, 1, 2] 1 2
  2. B. [2, 2] [0, 2, 4] 2 2
  3. C. [1, 1] [0, 1] 1 2
  4. D. [2, 2] [0, 2, 4] 1 2

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

A class body is not an enclosing scope for functions or comprehensions defined inside it. Only the FIRST iterable of a comprehension is evaluated in the class body, so range(x + 1) uses the class-level x = 2 → range(3). The element expressions run in the comprehension's own scope, which skips the class namespace and finds the global x = 1: a = [1, 1], b = [0, 1, 2]. The method m likewise returns the global 1, while K.x is 2. '[0, 1]' forgets that the outermost iterable does see the class variable.

More Python Programming questions

Exams that ask this topic