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 <rep...@bugs.python.org>
<http://bugs.python.org/issue26361>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to