MCQ Hive stays free thanks to ads. Please disable your ad blocker for this site so content and features keep working.
Fundamental Programming
Variables & Scope
Beginner
Q
What does this Python code print?
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
ANameError
B[0, 1, 2]
C[2, 2, 2]
D[0, 0, 0]
Correct Answer:
C. [2, 2, 2]
Explanation:
Closures bind late: each lambda looks up i when it is called, and by then i is 2. Writing lambda i=i: i would capture the value at creation instead.
ALSO KNOW (related points):
• What is the value of an uninitialized local (automatic) int variable in C++? → Indeterminate (garbage); reading it is undefined behavior
• Which keyword lets a Python function assign a new value to a module-level variable? → global
• What happens if a const int variable is declared in C++ without an initializer (const int k;)? → Compilation error