Message260289
This is the standard behaviour of closures in Python. It's annoying, and often not what you expect, but it's not a bug.
Effectively, your dict or list contains five functions, each of which refer to the same variable "t". By the time the loop finishes, that variable has the value 4, so naturally all five functions see the same value for t.
The standard work-around is to use the default-argument trick to take a snapshot of the current value of the variable at the moment the function is created:
[(lambda x, t=t: x * t) for t in range(5)] |
|
Date |
User |
Action |
Args |
2016-02-15 00:17:25 | steven.daprano | set | recipients:
+ steven.daprano, Samuel.Ainsworth |
2016-02-15 00:17:25 | steven.daprano | set | messageid: <1455495445.13.0.820550062486.issue26361@psf.upfronthosting.co.za> |
2016-02-15 00:17:25 | steven.daprano | link | issue26361 messages |
2016-02-15 00:17:24 | steven.daprano | create | |
|