ProgrammingModerateTCS NQT · Wipro pattern
What is printed?
What is printed?
class Bag:
items = []
def add(self, x):
self.items.append(x)
a, b = Bag(), Bag()
a.add(1)
b.add(2)
print(a.items, Bag.items, a.items is b.items)- A. [2] [1] False
- B. [1, 2] [] False
- C. [1] [] False
- D. [1, 2] [1, 2] True
Correct answer: D. [1, 2] [1, 2] True
items is a class attribute, so every instance's self.items resolves to the same list object, which add changes in place.
More Python Programming questions
- What is printed? python print(max('bca'), min('bca', key=lambda c: (c, -ord(c))))
- What is printed? python from collections import deque d = deque([1, 2, 3]) d.extendleft([4, 5]) print(list(d))
- What is printed? python x = 'abc' print(x.replace('', '-'))
- What is printed? python try: 'abc'.split('') except ValueError as e: print(e)
- What is printed? python a = [1, 2, 3] for x in a: a.remove(x) print(a)
- What is printed? python print(10 -2, 10 2.0, 10 // 3.0)