[issue26361] lambda in dict comprehension is broken

Steven D'Aprano report at bugs.python.org
Sun Feb 14 19:17:25 EST 2016


Steven D'Aprano added the comment:

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)]

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26361>
_______________________________________


More information about the Python-bugs-list mailing list