ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
class Cart:
def __init__(self, items=[]):
self.items = items
a = Cart(); b = Cart(); c = Cart([])
a.items.append("pen")
c.items.append("ink")
print(b.items, len(Cart.__init__.__defaults__[0]))- A. [] 0
- B. ['pen', 'ink'] 2
- C. [] 1
- D. ['pen'] 1
Correct answer: D. ['pen'] 1
a and b both store the single default list, so b.items shows 'pen' and the stored default now has length 1. c was given its own list, so 'ink' does not leak.
More Python Programming questions
- What is printed? python fs = [] for i in range(3): fs.append(lambda x: x + i) i = 10 print([f(1) for f in fs])
- What is printed? python def make(): fs = [] for i in range(3): fs.append(lambda: i) i = "z" return fs print([f() for f in make()])
- What is printed? python from functools import partial def p(a, b): return a 10 + b fs = [partial(p, i) for i in range(3)] gs = [lambda b…
- What is printed? python def counter(): count = 0 def inc(): nonlocal count count += 1 return count def peek(): return count return inc…
- What is printed? python x = 0 def outer(): x = 1 def mid(): def inner(): nonlocal x x += 10 return x return inner() r = mid() return r, x…
- What is printed? python def f(): try: print(y, end=" ") except NameError as e: print(type(e).name, end=" ") y = 1 y = 5 f() print(y)