a=[ lambda t: t**n for n in range(4) ]

Scott David Daniels Scott.Daniels at Acm.Org
Fri Apr 22 19:44:22 EDT 2005


Terry Hancock wrote:
> On Friday 22 April 2005 05:18 pm, mehmetmutigozel at gmail.com wrote:
> 
> Perhaps you don't know how to call such functions?  E.g.:
> 
> a=[ lambda t: t**n for n in range(4) ]
> 
> 
>>>>a[2](3)
> 
> 27

Didn't you notice this was a funny value?
Maybe this example will show you what is going wrong:

 >>> a[0](3)
27
 >>> n = 10
 >>> a[3](2)
1024

See, the body of your anonymous function just looks for "the current
value of n" when it is _invoked_, not when it is _defined_.

Perhaps you mean:

      a = [lambda t, n=n: t**n for n in range(4)]

which captures the value of n as a default parameter at definition time.
In that case you get:

 >>> a = [lambda t, n=n: t**n for n in range(4)]
 >>> a[0](1024)
1
 >>> a[1](512)
512
 >>> a[2](16)
256
 >>> a[3](4)
64

--Scott David Daniels
Scott.Daniels at Acm.Org





More information about the Python-list mailing list