ProgrammingVery hardProduct company OA
What is printed?
What is printed?
d = dict.fromkeys("ab", [])
d["a"].append(1)
d["b"] = d["b"] + [2]
d["a"] += [3]
g = [[]] * 2 + [[] for _ in range(2)]
g[0].append(7); g[2].append(8)
print(d, g)- A. {'a': [1, 3], 'b': [2]} [[7], [], [8], []]
- B. {'a': [1, 3], 'b': [1, 2]} [[7], [7], [8], []]
- C. {'a': [1, 3], 'b': [1, 2, 3]} [[7], [7], [8], [8]]
- D. {'a': [1, 2, 3], 'b': [1, 2, 3]} [[7], [7], [8], []]
Correct answer: B. {'a': [1, 3], 'b': [1, 2]} [[7], [7], [8], []]
dict.fromkeys uses the SAME list object as the value of every key, so the append through 'a' is visible through 'b' ([1]). d['b'] + [2] builds a new list [1, 2] and rebinds only 'b', breaking the sharing; the later in-place += through 'a' therefore changes only the original list → [1, 3]. In g, [[]] * 2 repeats one list twice (both show 7), while the comprehension creates two separate lists (only one shows 8).
More Python Programming questions
- A log pipeline must remove duplicate event ids from a list xs of n = 2·10⁵ integers while keeping the order of first occurrence. Four…
- What is printed? python class Base: registry = [] def initsubclass(cls, kw): cls.registry.append(cls.name) cls.tag = kw.get("tag"…
- What is printed? python class CM: def init(self, name, swallow): self.name, self.swallow = name, swallow def enter(self): print("in" +…
- What is printed? python import bisect a = [1, 3, 3, 3, 7] i, j = bisect.bisectleft(a, 3), bisect.bisectright(a, 3) bisect.insortleft(a…
- What is printed? python from itertools import groupby s = "aabbbaac" g1 = [(k, len(list(v))) for k, v in groupby(s)] g2 = {k: len(list(v))…
- What is printed? python print("abc" 2 + "d", len("abc" 0))