ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
t = ([1],)
try:
t[0] += [2]
except TypeError:
pass
try:
t[0] = t[0] + [3]
except TypeError:
pass
print(t)- A. ([1],)
- B. ([1, 2, 3],)
- C. ([1, 2],)
- D. ([1, 3],)
Correct answer: C. ([1, 2],)
t[0] += [2] first extends the list in place (succeeds) and only then fails on the tuple item assignment, so 2 sticks. t[0] = t[0] + [3] builds a new list and fails on assignment without touching the original, so 3 is lost.
More Python Programming questions
- What is printed? python x = [1, 2, 3] y = x x[:] = [7] x = x + [8] print(y, x)
- What is printed? python m = [[0] 2 for in range(2)] n = m.copy() n[0][0] = 5 n[1] = [6, 6] print(m)
- What is printed? python d = {"k": []} e = dict(d) f = {k: v[:] for k, v in d.items()} d["k"].append(1) e["k"] += [2] f["k"] += [3]…
- What is printed? python s = "abc" t = s s += "d" L = [1] M = L L += [2] print(t, M)
- What is printed? python row = [0] 3 grid = [row, row[:], row] grid[0][1] = 4 grid[1][2] = 7 print(grid[2], grid[1])
- What is printed? python def f(x, acc={}): acc[x] = len(acc) return acc a = f("p") b = f("q", {}) c = f("r") print(a is c, a, b)