ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE
What does the following Python 3 code print? fs = [lambda: i * 5 for i in range(3)] print([f() for f in fs])
- A. [0, 5, 10]
- B. 10
- C. [15, 15, 15, 15]
- D. [10, 10, 10]
Correct answer: D. [10, 10, 10]
Closures capture the variable i, not its value; after the loop i equals n−1, so every lambda sees that final value. Output: [10, 10, 10].
More Python Programming questions
- What does the following Python 3 code print? d = {} for w in ["nut","kheer","tea","oat","nut","vada"]: d[w[0]] = d.get(w[0], 0) + 1…
- What does the following Python 3 code print? s = "banana split" print("-".join(s.split("n")[1:]))
- What does the following Python 3 code print? from functools import lrucache calls = 0 @lrucache(None) def f(n): global calls calls += 1…
- What does the following Python 3 code print? a, b = set([12,12,1,7,1]), set([12,12,3,10,6,10]) print(sorted(a ^ b), len(a - b))
- What does the following Python 3 code print? def mk(): c = 0 def inc(): nonlocal c c += 2 return c return inc a, b = mk(), mk() for in…
- What does the following Python 3 code print? a, b, c = 25, 3, 17 print((a << b) ^ c, a & ~c, (a | c) >> b)