Question
Option 3 : [30, 30, 30, 30] / [30, 30, 30, 30]
Detailed Solution
सही उत्तर [30, 30, 30, 30] / [30, 30, 30, 30] है।
Question:
What is the output of the following Python code? `fs = []` / `for n in range(4):` / ` fs.append(lambda: n * 10)` / `print([g() for g in fs])` / निम्नलिखित Python कोड का आउटपुट क्या होगा? `fs = []` / `for n in range(4):` / ` fs.append(lambda: n * 10)` / `print([g() for g in fs])`
Correct Answer: [30, 30, 30, 30] / [30, 30, 30, 30]
The lambdas capture the variable `n` by reference (late binding), not its value at creation time, so when called after the loop, all four see the final value 3, giving 3 * 10 = 30 each. The trap is assuming each lambda freezes the loop value. / lambda variable `n` को मान से नहीं, reference से capture करते हैं (late binding), अतः लूप के बाद बुलाने पर चारों को अंतिम मान 3 दिखता है, जिससे प्रत्येक 3 * 10 = 30 देता है। जाल यह मानना है कि हर lambda लूप का मान freeze कर लेता है।