ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita
What is printed?
What is printed?
g = [[0] * 3] * 2 g[0][1] = 5 h = [[0] * 3 for _ in range(2)] h[0][1] = 5 print(g, h)
- 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. [[0, 0, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
Correct answer: B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
[[0]*3]*2 repeats one inner list object, so changing g[0][1] changes both rows. The list comprehension builds separate rows, so only the first row of h changes.
More Python Programming questions
- What is printed? python import heapq h = [] for w, name in [(2, 'b'), (1, 'z'), (2, 'a'), (1, 'c')]: heapq.heappush(h, (w, name)) out = []…
- What is printed? python recs = [('a', 2), ('b', 1), ('c', 2), ('d', 1)] print([n for n, v in sorted(recs, key=lambda r: r[1]…
- What is printed? python pairs = list(zip([1, 2, 3], 'ab', [True])) print(pairs, len(list(zip())))
- What is printed? python def threeless(a, t): a = sorted(a) n = len(a) c = 0 for i in range(n - 2): l, r = i + 1, n - 1 while l < r: if…
- What is printed? python import heapq def rooms(iv): iv = sorted(iv) h = [] for s, e in iv: if h and h[0] <= s: heapq.heapreplace(h, e)…
- For a Python dict d with n entries, which operation costs O(n) rather than O(1) on average?