This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients Samuel.Ainsworth, steven.daprano
Date 2016-02-15.00:17:24
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1455495445.13.0.820550062486.issue26361@psf.upfronthosting.co.za>
In-reply-to
Content
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)]
History
Date User Action Args
2016-02-15 00:17:25steven.dapranosetrecipients: + steven.daprano, Samuel.Ainsworth
2016-02-15 00:17:25steven.dapranosetmessageid: <1455495445.13.0.820550062486.issue26361@psf.upfronthosting.co.za>
2016-02-15 00:17:25steven.dapranolinkissue26361 messages
2016-02-15 00:17:24steven.dapranocreate