ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE
What does the following Python 3 code print? fs = [lambda: i * 2 for i in range(4)] print([f() for f in fs])
- A. 6
- B. [8, 8, 8, 8, 8]
- C. [6, 6, 6, 6]
- D. [0, 2, 4, 6]
Correct answer: C. [6, 6, 6, 6]
Closures capture the variable i, not its value; after the loop i equals n−1, so every lambda sees that final value. Output: [6, 6, 6, 6].
More Python Programming questions
- What does the following Python 3 code print? a, b = set([2,10,5,12,11,10]), set([12,5,9,3]) print(sorted(a ^ b), len(a - b))
- What does the following Python 3 code print? def mk(): c = 0 def inc(): nonlocal c c += 4 return c return inc a, b = mk(), mk() for in…
- What does the following Python 3 code print? s = "committee" print(s.count("m"), s.find("m"), s.rfind("m"), s.index("m", s.find("m") + 1)…
- What does the following Python 3 code print? a, b = [3,7,3,8], [4,1,7,7] print(list(map(lambda p: p[0] p[1], zip(a, b))), len(list(zip(a…
- What does the following Python 3 code print? a, b = set([11,9,12,1,11]), set([3,11,11,5,7,4]) print(sorted(a ^ b), len(a - b))
- What does the following Python 3 code print? def mk(): c = 0 def inc(): nonlocal c c += 4 return c return inc a, b = mk(), mk() for in…