ProgrammingHardPython · GATE DA · Advanced
What is printed?
What is printed?
funcs = []
for i in range(3):
funcs.append(lambda x=i: x * 10)
funcs.append(lambda: i * 10)
print([f() for f in funcs])- A. [0, 0, 10, 10, 20, 0]
- B. [0, 20, 10, 20, 20, 20]
- C. [0, 0, 10, 10, 20, 20]
- D. [0, 20, 10, 10, 20, 0]
Correct answer: B. [0, 20, 10, 20, 20, 20]
Default arguments freeze i at definition (0, 10, 20), but the plain lambdas read the global i at call time, when the loop has left i = 2 (20 each).
More Python Programming questions
- What is printed? python class Tag: items = [] n = 0 def add(self, v): self.items += [v] self.n += 1 a, b = Tag(), Tag() a.add('x')…
- What is printed? python x = 10 class K: x = 20 ys = [x + i for i in range(2)] print(K.ys)
- What is printed? python import itertools data = [1, 1, 2, 1, 1, 1, 3] print([(k, len(list(g))) for k, g in itertools.groupby(data)])…
- What is printed? python class P: def init(self, v): self.v = v def eq(self, o): return self.v == o.v s = set() try: s.add(P(1)) except…
- What is printed? python def make(): n = 0 def inc(): n += 1 return n return inc try: print(make()()) except Exception as e…
- What is printed? python import copy a = [1, 2] b = [a, a] c = copy.deepcopy(b) d = copy.copy(b) c[0].append(3) print(b, c[0] is c[1], d[0]…