ProgrammingModerateProduct-company MCQ pattern
What is printed?
What is printed?
x = [[0] * 3] * 2 y = [[0] * 3 for _ in range(2)] x[0][1] = 5 y[0][1] = 5 print(x, y)
- A. [[0, 5, 0], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
- B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
- C. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 5, 0]]
- D. [[5, 5, 5], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
Correct answer: B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
Multiplying the outer list copies the REFERENCE to the same inner list twice, so a change through x[0] shows in x[1]. The comprehension builds a new inner list each time. This is the classic 2-D grid bug.
More Python Programming questions
- What is printed? python def add(item, bucket=[]): bucket.append(item) return bucket a = add(1) b = add(2) c = add(3, []) print(a, b, c, a…
- What is printed? python fs = [lambda: i i for i in range(4)] gs = [lambda i=i: i i for i in range(4)] print([f() for f in fs], [g() for g…
- What is printed? python s = "abcdefgh" print(s[1:6:2], s[::-3], s[-3:-1], len(s[5:2]))
- What is printed? python def gen(): for i in range(3): x = yield i print("got", x, end="; ") g = gen() print(next(g), end="; ")…
- What is printed? python a = 256; b = 256 c = [1, 2]; d = [1, 2] print(a == b, c == d, c is d, c[:] is c)
- What is printed? python t = (1, [2, 3], 4) try: t[1] += [5] except TypeError as e: print("error", end=" ") print(t)