ProgrammingModerateTCS NQT · Infosys pattern
What is printed?
What is printed?
import copy a = [[1, 2], [3]] b = copy.copy(a) c = copy.deepcopy(a) a[0].append(9) a.append([4]) print(b, c)
- A. [[1, 2, 9], [3], [4]] [[1, 2], [3]]
- B. [[1, 2, 9], [3]] [[1, 2], [3]]
- C. [[1, 2], [3]] [[1, 2], [3]]
- D. [[1, 2, 9], [3]] [[1, 2, 9], [3]]
Correct answer: B. [[1, 2, 9], [3]] [[1, 2], [3]]
A shallow copy makes a new outer list but shares the inner lists, so appending 9 to a[0] shows in b, while appending [4] to a does not. deepcopy copies the inner lists too, so c is unaffected.
More Python Programming questions
- What is printed? python print(bool([]), bool([0]), bool(""), bool(" "), None == False, 0 == False)
- What is printed? python def countcalls(fn): def wrapper(a): wrapper.calls += 1 return fn(a) wrapper.calls = 0 return wrapper @countcalls…
- What is printed? python def make(): acc = [] for i in range(3): def f(x, i=i): return x i acc.append(f) acc.append(lambda x: x + i) return…
- What is printed? python class A: def go(self): return ["A"] class B(A): def go(self): return ["B"] + super().go() class C(A): def…
- What is printed? python def inner(): x = yield 1 y = yield x + 1 return x y def outer(): r = yield from inner() yield r yield from…
- What is printed? python def reg(name, seen={}, order=[]): if name not in seen: seen[name] = len(order) order = order + [name] return…