[Tutor] Lambda?? Whaaaaat?

Dave Angel d at davea.name
Fri Aug 31 06:23:46 CEST 2012


On 08/30/2012 11:39 PM, Scurvy Scott wrote:
> I'm fairly new to python having recently completed LPTHW. While randomly reading stack overflow I've run into "lambda" but haven't seen an explanation of what that is, how it works, etc.
> Would anyone care to point me in the right direction?

lambda is an alternative syntax for defining a function.  However, the
function has no name, and can be defined in the middle of another
expression.  The main constraint is that a lambda function can consist
only of a single expression.  No statements, no if's, no loops.  It's
main usefulness is for callbacks, for example for a sort operation, or
gui event handlers.

if you had a function that returned the square of its argument, you
might define it as follows:

def square(x):
     return x*x

You could accomplish the same thing by the lambda function:

square = lambda x : x*x

Here we create a function with lambda, then bind it to the name square. 
No benefit, but it shows the syntax.

More interesting is if we want to sort a list of two-tuples, using the
3rd element of each as our sort key.

mylist.sort(key=lambda x : x[2])

There are other ways to accomplish that (and I think there's a standard
library function for it), but maybe it shows you what it could be used
for.  The function is generated, the sort happens, and the function is
discarded.

(all code untested)

-- 

DaveA



More information about the Tutor mailing list