[Tutor] string to list

Alan Gauld alan.gauld at btinternet.com
Thu Feb 11 09:29:43 CET 2010


"Owain Clarke" <simbobo at cooptel.net> wrote 

> I would love a really clear explanation of lambda!

lambda returns an anonymous function - a function without a name.

When we define a function normally we use something like:

def square(x):
   return x*x

That creates a function that has the name square

We can do the same with lambda:

square = lambda x : x*x

which is equivalent to the def form.

This is useful where we only need the function 
temporarily, such as to return a sort key or in 
building GUI controls.

The general shape of lambda is:

lambda <parameter list> : <return expression>

So in your case

lambda x: x[0]

could be replaced with

def first(x): return x[0]

lst.sort(key=first)

But since you don't use first() for anything else 
you don't really need a named function so you 
can use a lambda. lambda is best used for 
short single line functions. In fact you can only 
use it where the body of the function can be 
expressed as a single expression.

You will find more explanation and examples 
in the Functional Programming topic in my tutorial.

HTH
-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list