Python function lambda function volatility

I tried the following code in a 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 

It seems rather odd whether to return 0 and 13 to these last two calls. I tried looking directly at the test itself, and it seems that all the functions in it are different.

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

Any idea why they all behave the same?

+6
source share

Source: https://habr.com/ru/post/945158/


All Articles