ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
grid = [[0, 0]] * 2 copy1 = list(grid) copy2 = [row[:] for row in grid] grid[0][0] = 1 grid[1] = [5, 5] print(copy1, copy2, grid)
- A. [[0, 0], [0, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
- B. [[1, 0], [0, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
- C. [[1, 0], [5, 5]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
- D. [[1, 0], [1, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
Correct answer: D. [[1, 0], [1, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
[[0, 0]] * 2 holds the SAME inner list twice. list(grid) is a shallow copy: a new outer list pointing at that same inner list, so grid[0][0] = 1 shows up in both rows of copy1. copy2 copied each row, so it is unaffected. grid[1] = [5, 5] rebinds a slot of grid only; copy1's slots still point at the shared row.
More Python Programming questions
- What is printed? python vals = iter([3, 1, 0, 4, 0]) print(list(iter(lambda: next(vals), 0)), list(vals))
- What is printed? python class Acc: def init(self): self.items = [] def iadd(self, v): self.items.append(v) a = Acc() b = a a += 1 print(a…
- What is printed? python def f(): log = [] try: log.append("t") raise ValueError("v") except ValueError as e: log.append("e") raise…
- What is printed? python it = iter(range(10)) print(5 in it, next(it), 2 in it, list(it), 9 in range(10))
- What is printed? python calls = [] def chk(x): calls.append(x) return x > 2 r1 = any(chk(x) for x in [1, 3, 5]) r2 = all([chk(x) for x in…
- What is printed? python a = [1, 2] b = [a] 3 a = 2 b[0].append(9) print(b[2], len(b))