Tim Peters added the comment:
This behavior is intended and expected, so I'm closing this.
As has been explained, in any kind of function (whether 'lambda' or 'def'), a
non-local variable name resolves to its value at the time the function is
evaluated, not the value it _had_ at the time
Vedran Čačić added the comment:
Yes, I never really understood what problem people have with it. If I manually
say
i = 0
f = lambda a: a[i]
i = 1
g = lambda a: a[i]
why does anyone expect functions f and g to be different? They have the same
argument, and do the same thing with it. The
Karthikeyan Singaravelan added the comment:
This could also help in understanding late binding that happens with the
lambdas in the report :
https://docs.python-guide.org/writing/gotchas/#late-binding-closures
--
nosy: +xtreak
___
Python tracker
Vedran Čačić added the comment:
Why exactly is [2,3] expected? In the first example, the inner list has two
functions that are _exactly the same_. Each of them takes a, grabs i from outer
scope, and returns a[i]. (And of course, at the moment of evaluation of these
functions, i is 1.)
Do
Alexey Burdin added the comment:
x=[2,3]
[f(x) for f in [(lambda a:a[i]) for i in [0,1]]]
#the expected output is [2,3] but actual is [3,3]
[f(x) for f in [lambda a:a[0],lambda a:a[1]]]
#results [2,3] normally
--
___
Python tracker
New submission from Alexey Burdin :
>>> x=[2,3]
>>> [f(x) for f in [(lambda a:a[i]) for i in [0,1]]]
[3, 3]
>>> [f(x) for f in [lambda a:a[0],lambda a:a[1]]]
[2, 3]
--
components: Interpreter Core
messages: 357586
nosy: Alexey Burdin
priority: normal
severity: normal
status: open