Filmmaker, Video Editor, Motion Graphics Designer, and Photographer in Cairo, Egypt.
Keeping notes to remember.. You may consider it some sort of Documentation.

Stay In Touch

Saturday, August 22, 2009

Python's Lambda

Python's lambda allows you to declare a one-line nameless minifunction on the fly. The format is:

lambda parameter(s): expression using the parameter(s)

It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...

>>> def f(x):
... return x*2
>>> f(3)
>>> g = lambda x: x*2
>>> g(3)
>>> (lambda x: x*2)(3)

This is a lambda function that accomplishes the same thing as the normal function above it. Note the abbreviated syntax here: there are no parentheses around the argument list, and the return keyword is missing (it is implied, since the entire function can only be one expression). Also, the function has no name, but it can be called through the variable it is assigned to.

You can use a lambda function without even assigning it to a variable. Not the most useful thing in the world, but it just goes to show that a lambda is just an in-line function.

To generalize, a lambda function is a function that takes any number of arguments (including optional arguments) and returns the value of a single expression. lambda functions can not contain commands, and they can not contain more than one expression. Don’t try to squeeze too much into a lambda function; if you need something more complex, define a normal function instead and make it as long as you want.

lambda functions are a matter of style. Using them is never required. It could be used in places where you want to encapsulate specific, non-reusable code without littering your code with a lot of little one-line functions.