Question

1.
2.
3.
4.
Answer (Detailed Solution Below)

Option 3 : [30, 30, 30, 30] / [30, 30, 30, 30]

Advertisement

Detailed Solution

सही उत्तर [30, 30, 30, 30] / [30, 30, 30, 30] है।

Key Points
Helpful?
PrepSnapprepsnap.in • Part -A

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])`

1.
[0, 10, 20, 30] / [0, 10, 20, 30]
2.
[0, 0, 0, 0] / [0, 0, 0, 0]
3.
[30, 30, 30, 30] / [30, 30, 30, 30]
4.
Error — n is not defined inside lambda / त्रुटि — lambda के अंदर n परिभाषित नहीं है

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 कर लेता है।

Downloaded from PrepSnap (prepsnap.in)