ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
d = dict.fromkeys(range(3), 0)
for k in d:
d[k] += k
e = {k: [] for k in "ab"}
e["a"].append(1)
f = dict.fromkeys("ab", [])
f["a"].append(1)
print(d, e, f)- A. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': [1]} {'a': [1], 'b': [1]}
- B. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': []} {'a': [1], 'b': []}
- C. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': []} {'a': [1], 'b': [1]}
- D. RuntimeError
Correct answer: C. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': []} {'a': [1], 'b': [1]}
Changing values while iterating is allowed (only size changes are not). fromkeys uses one shared object for every value, so a mutable default is shared, unlike a comprehension that builds a new list per key.
More Python Programming questions
- What is printed? python x = None print(x is None, x == None, bool(None), type(None).name, None is not False)
- What is printed? python class P: pass p = P() p.n = 1 p.n += 1 P.m = 10 q = P() q.m += 5 print(p.n, P.m, q.m, p.m, vars(q))
- What is printed? python def makeacc(): total = [] def add(x): total.append(x) return sum(total) def reset(): nonlocal total total = []…
- What is printed? python adders = [lambda x, n=n: x + n for n in range(3)] mults = list(map(lambda n: (lambda x: x n), range(3)))…
- What is printed? python def outer(): fs = [] for i in range(3): def f(j=None): return i if j is None else j fs.append(f) if i == 1: break…
- What is printed? python x = "global" def f(): return [x for in range(1)][0] def g(): x = "local" return (lambda: x)() def h(): return…