ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
fs = [lambda: i * i for i in range(4)] gs = [lambda i=i: i * i for i in range(4)] print([f() for f in fs], [g() for g in gs])
- A. [9, 9, 9, 9] [0, 1, 4, 9]
- B. [0, 1, 4, 9] [0, 1, 4, 9]
- C. [9, 9, 9, 9] [9, 9, 9, 9]
- D. [0, 1, 4, 9] [9, 9, 9, 9]
Correct answer: A. [9, 9, 9, 9] [0, 1, 4, 9]
Closures capture the variable, not its value (late binding): when the lambdas run, i is 3, so every call gives 9. A default argument i=i is evaluated at definition time and freezes each value.
More Python Programming questions
- What is printed? python s = "abcdefgh" print(s[1:6:2], s[::-3], s[-3:-1], len(s[5:2]))
- What is printed? python def gen(): for i in range(3): x = yield i print("got", x, end="; ") g = gen() print(next(g), end="; ")…
- What is printed? python a = 256; b = 256 c = [1, 2]; d = [1, 2] print(a == b, c == d, c is d, c[:] is c)
- What is printed? python t = (1, [2, 3], 4) try: t[1] += [5] except TypeError as e: print("error", end=" ") print(t)
- What is printed? python def f(): try: return "try" finally: print("finally", end=" ") def g(): try: return "try" finally: return "finally"…
- What is printed? python nums = [3, 1, 2] r = nums.sort() s = sorted(nums, reverse=True) print(r, nums, s)