7

I've tried the following code in the python interpreter:

>>> def say(n):
...   print n
... 
>>> say(12)
12
>>> test = []
>>> for each in range(30):
...   test.append(lambda: say(each))
... 
>>> test[0]()
29
>>> test[13]()
29

This seems quite weird, shouldn't it return 0 and 13 on those last two calls. I've tried looking directly at test itself, and it seems like all the functions in it are distinct

>>> test[0] == test[1]
False
>>> test[0]
<function <lambda> at 0x203e140>
>>> test[1]
<function <lambda> at 0x203e1b8>

Any idea why they're all behaving the same way?

  • 5
    Because the value of `each` is not bound at lambda creation time; it is looked up when you *call* the lambda. – Martijn Pieters May 16 '13 at 11:54
  • The *answers* the are similar, but the questions are a bit different. Or at least I can imagine someone with Ben's problem might see the other question and not see the connection. – Adrian Ratnapala May 16 '13 at 11:56
  • @MartijnPieters your point is something I came across recently while thinking about why `f = lambda: f()` is valid yet, `a = {"me":a}` ins't. The former is only valid because `f()` isn't executed until later. – HennyH May 16 '13 at 11:56
  • @AdrianRatnapala: There is no difference between functions and lambdas in this regard. – Martijn Pieters May 16 '13 at 11:59

0 Answers0