Question discussion

What is the output of the following Python code?class A: l = [] a, b = A(), A() a.l.append(1) b.l.append(2) print(A.l, len(a.l))

1123Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Python code?

class A:
    l = []
a, b = A(), A()
a.l.append(1)
b.l.append(2)
print(A.l, len(a.l))
  • A[1] 1
  • B[2] 1
  • C[1, 2] 2
  • D[] 0
Correct answer: C

Explanation

l is a class attribute shared by all instances, so both appends go into the same list.

Discussion 0

Nobody has replied yet. Start the discussion!