Help with lambda

News123 news123 at free.fr
Wed Feb 24 16:21:59 EST 2010


Jonathan Gardner wrote:
> On Feb 18, 4:28 am, lallous <elias.bachaal... at gmail.com> wrote:
>> f = [lambda x: x ** n for n in xrange(2, 5)]
> 
> This is (pretty much) what the above code does.
> 
>>>> f = []
>>>> n = 2
>>>> f.append(lambda x: x**n)
>>>> n = 3
>>>> f.append(lambda x: x**n)
>>>> n = 4
>>>> f.append(lambda x: x**n)
>>>> n = 5
>>>> f.append(lambda x: x**n)
> 
> Now, when you call f[0], you are calling "lambda x: x**n". What is
> "n"?
> 


If you use a newer version of python (>= 2.5), then you might want to
look at functools.partial.


> def pow(a,n):
>     return a ** n
> 
> f = [functools.partial(pow,n=n) for n in xrange(2, 5)]
> 


Not sure, whether there's any (dis)advantage over
> f = [lambda x,n=n: x ** n for n in xrange(2, 5)]
or
> f = [lambda x,n=n: pow(x,n) for n in xrange(2, 5)]




bye

N






More information about the Python-list mailing list