ProgrammingModerateProduct-company MCQ pattern
What is printed?
What is printed?
def add(item, bucket=[]):
bucket.append(item)
return bucket
a = add(1)
b = add(2)
c = add(3, [])
print(a, b, c, a is b)- A. [1] [2] [3] False
- B. [1] [1, 2] [3] False
- C. [1, 2] [1, 2] [1, 2, 3] True
- D. [1, 2] [1, 2] [3] True
Correct answer: D. [1, 2] [1, 2] [3] True
The default list is created once, when def runs, and shared by every call that omits the argument. a and b are the same list, which now holds [1, 2]. Passing a fresh list for c avoids the sharing. Use bucket=None and create the list inside.
More Python Programming questions
- What is printed? python fs = [lambda: i i for i in range(4)] gs = [lambda i=i: i i for i in range(4)] print([f() for f in fs], [g() for g…
- What is printed? python s = "abcdefgh" print(s[1:6:2], s[::-3], s[-3:-1], len(s[5:2]))
- What is printed? python def gen(): for i in range(3): x = yield i print("got", x, end="; ") g = gen() print(next(g), end="; ")…
- What is printed? python a = 256; b = 256 c = [1, 2]; d = [1, 2] print(a == b, c == d, c is d, c[:] is c)
- What is printed? python t = (1, [2, 3], 4) try: t[1] += [5] except TypeError as e: print("error", end=" ") print(t)
- What is printed? python def f(): try: return "try" finally: print("finally", end=" ") def g(): try: return "try" finally: return "finally"…