lambda
Terry Reedy
tjreedy at udel.edu
Sat Apr 22 01:06:02 EDT 2006
<rubbishemail at web.de> wrote in message
news:1145642409.389741.39680 at g10g2000cwb.googlegroups.com...
> Hello,
>
> I need your help understanding lambda (and doing it a better way
> without).
>
> f = lambda x : x*x
There is no reason to ever write name=lambda...
def f(x): return x*x
is better because it attaches the name to the function for tracebacks.
> # this is a list of functions
> [f for y in range(1,5)]
>
> [f for y in range(1,5)][0](2)
> # returns 4, as expected
>
>
> # ok now I want a list like
> # [x^2, 2*x^2, 3*x^2,...]
Given:
def makef(multiplier):
def f(x): return multiplier*x*x
return f
> [f*y for y in range(5)]
I believe
[makef(y) for y in range(5)]
will do what you want.
The slightly abbreviated lambda form is never necessary, that I know of,
and notoriously confusing when used in list comprehensions. So I advise
don't.
Terry Jan Reedy
More information about the Python-list
mailing list