"Owain Clarke" <[email protected]> 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/

_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to