Re: [Tutor] Python Cookbook
by Erik Price other posts by this author
Aug 26 2002 2:15PM messages near this date
Re: [Tutor] Python Cookbook
|
[Tutor] Why lambda could be considered evil
On Monday, August 26, 2002, at 09:54 AM, Yigal Duppen wrote:
> List comprehensions (LCs) provide a much better way of getting the
> derived
> list:
> derived = [ z.getX() for z in l ]
>
> As you can see, this requires no anonymous functions and is perfectly
> OO.
>
> The advantage of this becomes even clearer if you want to map AND
> filter.
> Let's say we only want the even values and that we have no 'odd' or
> 'even'
> function.
>
> derivedEven = filter(lambda n: n % 2 == 0, map(lambda z: z.getX(), l))
>
> Argl! What does this do? All we have is the 'descriptive' variable name.
>
> derivedEven = [ z.getX() for z in l if z.getX() % 2 == 0 ]
>
> Much better! But then again, LCs are also a matter of taste :)
Ah... very clear now. I hadn't considered that LCs are useful because,
like lambda, they don't require you to specify a specific type (such as
in "derived = map(Foo.getX, l)"), so they can be useful in situations
where you're trying to use polymorphism or something. Great example.
But what -is- the problem that some people have with lambda? (You
mention that you don't have a problem with it, but that implies that
others do.)
One last question -- in your final example above, you have an "if"
statement FOLLOWING the "main" part of the list comprehension. Is this
a normal Python construction or something that is allowed for list
comprehensions only? I have seen that sort of construction in Perl:
print "Correct" if ($correct);
But I haven't seen it in Python.
Thanks again.
Erik
--
Erik Price
email: erikprice@[...].com
jabber: erikprice@[...].org
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Erik Price
Danny Yoo
Erik Price
Yigal Duppen
Erik Price
Scot W. Stevenson
Yigal Duppen
|