ProgrammingHardAccenture pattern
What is printed?
What is printed?
d = {}
d.setdefault("a", []).append(1)
d.setdefault("a", []).append(2)
d.setdefault("b", []).append(3)
print(d)- A. {'a': [1], 'b': [2, 3]}
- B. {'a': [1, 2], 'b': [3]}
- C. {'a': [2], 'b': [3]}
- D. {'a': [1], 'b': [3]}
Correct answer: B. {'a': [1, 2], 'b': [3]}
setdefault('a', []) creates the list [] only the FIRST time key 'a' is missing, then returns the SAME existing list on later calls; so both appends to 'a' go to one shared list, giving [1, 2]. 'b' gets its own fresh list with just 3.
More Python Programming questions
- What is printed? python class A: def len(self): return 0 a = A() print(bool(a)) if a: print("truthy") else: print("falsy")
- What is printed? python x = 10 class C: x = 20 def m(self): return x c = C() print(c.m(), C.x)
- What is printed? python def f(x, y=10): def g(): return x + y y = 20 return g() print(f(1))
- What is printed? python nums = [1, 2, 3] doubled = list(map(lambda x: x 2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums))…
- What is printed? python class A: def call(self, x): return x 2 a = A() print(a(5), callable(a))
- What is printed? python class Node: def init(self, val, children=None): self.val = val self.children = children if children is not None…