ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def f(a, b=[]):
b = b + [a]
f.__defaults__ = (b,)
return b
print(f(1), f(2), f(3, []), f(4))- A. [1] [1, 2] [3] [1, 2, 4]
- B. [1] [2] [3] [4]
- C. [1] [1, 2] [3] [1, 2, 3, 4]
- D. [1] [1, 2] [3] [3, 4]
Correct answer: D. [1] [1, 2] [3] [3, 4]
Each call builds a new list and installs it as the new default via __defaults__. Even f(3, []), which ignores the default, stores [3] as the default, so f(4) returns [3, 4].
More Python Programming questions
- What is printed? python it = (x x for x in range(5)) first = next(it) rest = [v for v in it if v % 2 == 0] again = sum(1 for in it)…
- What is printed? python def g(): for i in range(3): try: yield i finally: print(f"f{i}", end=" ") for v in g(): if v == 1: break…
- What is printed? python def deco(cls): orig = cls.init def init(self, a): orig(self, a) self.ok = True cls.init = init return cls @deco…
- What is printed? python import functools @functools.singledispatch def show(x): return "obj" @show.register def (x: int): return "int"…
- What is printed? python def f(): x = 0 def inc(): nonlocal x x += 1 return x return [inc() for in range(3)], x print(f())
- What is printed? python def f(kw): return list(kw) print(f(b=1, a=2), f(dict(z=0), y=1), f({"1": 1}))