[Tutor] lambda

Steven D'Aprano steve at pearwood.info
Sun Mar 20 02:07:12 CET 2011


Ajit Deshpande wrote:
> I am trying to figure out where lambda functions can be useful. Has anyone
> used them in real world?

Of course. lambdas are especially useful for callback functions, which 
are especially common when doing GUI programming.


> From my reading so far, I hear people claim that lambda can be a useful
> replacement for small functions. Most examples  didn't make much sense to
> me. Why would anyone use a one liner anonymous function, if you never plan
> to use it elsewhere?

That's precisely the point -- why would you define a non-anonymous 
function that you only use once?

def spam(x):
     return x + something

register_handler(spam)  # Provide a callback to some part of your app
# never use spam again


is better written as:

register_handler(lambda x: x+something)


>  You would then be implementing the logic directly in
> the line, isn't it?. Functions are useful if they plan to get called
> multiple times within your code.

That's often the case, but not necessarily.



> For example:
> 
> add_one = lambda x: x + 1

This defines a function "add_one". This is equivalent to writing:

def add_one(x):
     return x+1

> In real world, why would I use a lambda for this. I would simply do:
> 
> add_one = x + 1

This takes the current value of x, adds one to it, and assigns it to the 
very badly named variable "add_one".


> Can you provide some useful use cases for lambda functions?

Sorting with comparison or key functions.
min or max with a key function.
Callbacks.
map
reduce
Solving numerical equations.

There are probably others, but they're the obvious ones.

Here's an example you can try:

text = """Li Europan lingues es membres del sam familie. Lor separat 
existentie es un myth. Por scientie, musica, sport etc, litot Europa usa 
li sam vocabular. Li lingues differe solmen in li grammatica, li 
pronunciation e li plu commun vocabules. Omnicos directe al desirabilite 
de un nov lingua franca: On refusa continuar payar custosi traductores."""
words = text.lower().split()
sorted(words)  # sort in alphabetical order


Now suppose you want to sort by the number of vowels. Here's how you can 
do it with an anonymous key function:

sorted(words, key=lambda word: sum(word.count(c) for c in 'aeiou'))


-- 
Steven



More information about the Tutor mailing list