@@ -206,6 +206,58 @@ an imported module. This clutter would defeat the usefulness of the ``global``
206206declaration for identifying side-effects.
207207
208208
209+ Why do lambdas defined in a loop with different values all return the same result?
210+ ----------------------------------------------------------------------------------
211+
212+ Assume you use a for loop to define a few different lambdas (or even plain
213+ functions), e.g.::
214+
215+ squares = []
216+ for x in range(5):
217+ squares.append(lambda: x**2)
218+
219+ This gives you a list that contains 5 lambdas that calculate ``x**2 ``. You
220+ might expect that, when called, they would return, respectively, ``0 ``, ``1 ``,
221+ ``4 ``, ``9 ``, and ``16 ``. However, when you actually try you will see that
222+ they all return ``16 ``::
223+
224+ >>> squares[2]()
225+ 16
226+ >>> squares[4]()
227+ 16
228+
229+ This happens because ``x `` is not local to the lambdas, but is defined in
230+ the outer scope, and it is accessed when the lambda is called --- not when it
231+ is defined. At the end of the loop, the value of ``x `` is ``4 ``, so all the
232+ functions now return ``4**2 ``, i.e. ``16 ``. You can also verify this by
233+ changing the value of ``x `` and see how the results of the lambdas change::
234+
235+ >>> x = 8
236+ >>> squares[2]()
237+ 64
238+
239+ In order to avoid this, you need to save the values in variables local to the
240+ lambdas, so that they don't rely on the value of the global ``x ``::
241+
242+ squares = []
243+ for x in range(5):
244+ squares.append(lambda n=x: n**2)
245+
246+ Here, ``n=x `` creates a new variable ``n `` local to the lambda and computed
247+ when the lambda is defined so that it has the same value that ``x `` had at
248+ that point in the loop. This means that the value of ``n `` will be ``0 ``
249+ in the first lambda, ``1 `` in the second, ``2 `` in the third, and so on.
250+ Therefore each lambda will now return the correct result::
251+
252+ >>> squares[2]()
253+ 4
254+ >>> squares[4]()
255+ 16
256+
257+ Note that this behaviour is not peculiar to lambdas, but applies to regular
258+ functions too.
259+
260+
209261How do I share global variables across modules?
210262------------------------------------------------
211263
0 commit comments