ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def f(x=[]):
x += [len(x)]
return x
def g(x=()):
x += (len(x),)
return x
print(f(), f(), g(), g())- A. [0] [0, 1] (0,) (0, 1)
- B. [0, 1] [0, 1] (0,) (0, 1)
- C. [0] [0] (0,) (0,)
- D. [0, 1] [0, 1] (0,) (0,)
Correct answer: D. [0, 1] [0, 1] (0,) (0,)
For a list, += mutates the shared default in place, and both calls return that same object, printed after both ran: [0, 1] twice. For a tuple, += creates a new tuple, so the default () never changes.
More Python Programming questions
- What is printed? python funcs = {} for name in ["inc", "dbl"]: if name == "inc": def op(v): return v + 1 else: def op(v): return v 2…
- What is printed? python gen = (x for x in range(3)) lst = [x for x in range(3)] print(type(gen).name, len(lst), sum(gen), sum(gen)…
- What is printed? python class A: def repr(self): return "A()" class B(A): def str(self): return "B!" print(str(A()), [B()], f"{B()}", "%s…
- What is printed? python x = 10 def f(x, y=x): x += 1 return x, y x = 20 print(f(5), f(y=1, x=2), x)
- What is printed? python for i in range(3): if i == 5: break else: print("else", i, end=" ") n = 0 while n < 3: n += 1 if n == 2: break…
- What is printed? python def find(xs, t): for i, x in enumerate(xs): if x == t: return i else: return -1 return "unreachable"…