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)
  1. A. {'a': [1, 3], 'b': [2]} [[7], [], [8], []]
  2. B. {'a': [1, 3], 'b': [1, 2]} [[7], [7], [8], []]
  3. C. {'a': [1, 3], 'b': [1, 2, 3]} [[7], [7], [8], [8]]
  4. 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

Exams that ask this topic