Let's Talk About Lambda Functions!

Yigal Duppen yduppen at xs4all.nl
Sun Jul 28 12:03:05 EDT 2002


> So I know what lambda functions are, they're syntax and how they're used.
> However I'm not sure *why* one would use a lambda function. What's the
> advantage that they offer over a regular function?

Back in the old days, before 2.2 came out with its list comprehensions, they 
had their use.

I am a big fan of constructs like map, filter and reduce; by using one 
function, they allow you to eliminate looping constructs from your code, 
keeping it shorter and (usually) clearer.


However, if you have a list of objects:
>>> class A:
...     def value(self):
...     return "x"
>>> list_of_as = [A(), A(), A()]

and you want to extract the values using map(), you needed to do:
>>> map(lambda x: x.value(), list_of_as)
['x', 'x', 'x']

Luckily, list comprehensions remove that need
>>> [x.value() for x in list_of_as]
['x', 'x', 'x']

Since I started to use list comprehensions, I haven't needed a single 
lambda.

YDD
-- 
.sigmentation fault



More information about the Python-list mailing list