ProgrammingVery hardInfosys · Python · Advanced
What is printed?
What is printed?
fs = [lambda x, i=i: x * i for i in range(3)] gs = [lambda x: x * i for i in range(3)] print([f(2) for f in fs], [g(2) for g in gs])
- A. [0, 2, 4] [4, 4, 4]
- B. [0, 2, 4] [0, 2, 4]
- C. [4, 4, 4] [4, 4, 4]
- D. [4, 4, 4] [0, 2, 4]
Correct answer: A. [0, 2, 4] [4, 4, 4]
The default argument i=i freezes each loop value; the plain lambdas look up i when called, after the loop ended with i = 2.
More Python Programming questions
- What is printed? python n = 1 xs = [1, 2, 3] g = (x for x in xs if x > n) xs = [10, 20] n = 2 print(list(g))
- What is printed? python print(f"{255:#x} {255:08b} {3.14159:.2f} {'ab':>4}|{12345.678:,.1f}")
- What is printed? python def fib(n, memo={}): if n < 2: return n if n not in memo: memo[n] = fib(n - 1) + fib(n - 2) return memo[n]…
- What is printed? python class T: def init(self, n): self.n = n def enter(self): print('in', self.n, end=' ') return self def exit(self…
- What is printed? python a = [1, 2, 3] a[1:2] = a a.insert(-1, 'x') a.insert(99, 'y') print(a, a.pop(-2), a.index(3))
- What is printed? python print(True + True, sum([True, False, True]), isinstance(True, int), [10, 20, 30][True], 'ab' False == '')