ProgrammingHardWipro NLTH · Python
What is printed?
What is printed?
a = [[0] * 2] * 2 a[0][0] = 1 b = [[0] * 2 for _ in range(2)] b[0][0] = 1 print(a, b)
- A. [[1, 0], [1, 0]] [[1, 0], [0, 0]]
- B. [[1, 0], [0, 0]] [[1, 0], [0, 0]]
- C. [[1, 0], [1, 0]] [[1, 0], [1, 0]]
- D. [[1, 0], [0, 0]] [[1, 0], [1, 0]]
Correct answer: A. [[1, 0], [1, 0]] [[1, 0], [0, 0]]
[[0]*2]*2 repeats a reference to one inner list, so both rows change; the comprehension builds two independent rows.
More Python Programming questions
- What is printed? python def f(n): try: if n == 0: raise ValueError return 10 // (n - 1) except ZeroDivisionError: return -1 except…
- What is printed? python a, b, c = range(5) x, (y, z) = 1, 'hey' print(a, b, c, x, y, z)
- What is printed? python from collections import Counter c = Counter('mississippi') print(c.mostcommon(2), c['z'], sorted(c.items())[:2])
- What is printed? python pts = [(2, 1), (1, 5), (2, 0), (1, 2)] print(sorted(pts, key=lambda p: (-p[0], p[1])), max(pts, key=lambda p: p[1]))
- What is printed? python import copy a = {'k': [1, 2]} b = a.copy() c = copy.deepcopy(a) a['k'].append(3) a['j'] = 0 print(b, c)
- What is printed? python m = map(lambda x: x 2, [1, 2, 3]) print(list(m), list(m), sum(map(int, '123')))