On Tuesday, September 27, 2016 at 9:09:55 PM UTC+13, Cpcp Cp wrote:
> >>> li=[lambda :x for x in range(10)]
Try
li = [(lambda x : lambda : x)(x) for x in range(10)]
print(li[0]())
print(li[9]())
0
9
--
https://mail.python.org/mailman/listinfo/python-list
I get it.Thanks!
--
https://mail.python.org/mailman/listinfo/python-list
Op 27-09-16 om 10:09 schreef cpx...@gmail.com:
li=[lambda :x for x in range(10)]
res=li[0]()
print res
> 9
>
> why?
Because there is no nested scope for the x variable.So your list looks
like this: [lambda :x, lambda :x, lambda :x, lambda :x, lambda :x,
lambda :x, lambda :x, lambda
cpx...@gmail.com wrote:
li=[lambda :x for x in range(10)]
res=li[0]()
print res
> 9
>
> why?
Look what happens if you look up x manually:
>>> li = [lambda :x for x in range(10)]
>>> x
9
So at this point x is 9 and a function written to return the value bound to
the name x will
cpx...@gmail.com writes:
li=[lambda :x for x in range(10)]
res=li[0]()
print res
> 9
>
> why?
Because each of the ten functions will report the final value of the
same x.
There are a couple of tricks to capture the transient value:
[lambda w=x: w for x in range(10)]
[(lambda w: