Data Structures & AlgorithmsHardTCS NQT Digital · Python semantics
Problem: What does the following print?
Problem: What does the following print?
x = [[0] * 2] * 2 x[0][1] = 5 print(x)
- A. [[0, 5], [0, 5]]
- B. [[0, 5], [0, 0]]
- C. [[0, 0], [0, 5]]
- D. [[5, 5], [0, 0]]
Correct answer: A. [[0, 5], [0, 5]]
[[0] * 2] * 2 repeats one inner list twice, so both rows are the same object and the write shows in both. Building the rows with a comprehension avoids this aliasing.
More Coding Interview Problems questions
- Problem: What does the following print? python print(0.1 + 0.2 == 0.3, round(2.5), round(3.5))
- Problem: What does the following print? python a = [1, 2, 3] b = a b += [4] print(a)
- Problem: What does the following print? python print(int('0b101', 0), int('101', 2), 7 // 2 2)
- Problem: What does the following print? python fs = [lambda: i for i in range(3)] print([f() for f in fs])
- Problem: What does the following print? python print(len({1, 2, 3} & {2, 3, 4} | {5}))
- Problem: What does the following print? python print('10' < '9', 10 < 9)