What does “lambda” mean in Python, and what’s the simplest way to use it?

Lambda, which originated from Lambda Calculus and (AFAIK) was first implemented in Lisp, is basically an anonymous function – a function which doesn’t have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:

>>> addTwo = lambda x: x+2
>>> addTwo(2)
4

This assigns addTwo to the anonymous function, which accepts 1 argument x, and in the function body it adds 2 to x, it returns the last value of the last expression in the function body so there’s no return keyword.

The code above is roughly equivalent to:

>>> def addTwo(x):
...     return x+2
... 
>>> addTwo(2)
4

Except you’re not using a function definition, you’re assigning an identifier to the lambda.

The best place to use them is when you don’t really want to define a function with a name, possibly because that function will only be used one time and not numerous times, in which case you would be better off with a function definition.

Example of a hash tree using lambdas:

>>> mapTree = {
...     'number': lambda x: x**x,
...     'string': lambda x: x[1:]
... }
>>> otype="number"
>>> mapTree[otype](2)
4
>>> otype="string"
>>> mapTree[otype]('foo')
'oo'

In this example I don’t really want to define a name to either of those functions because I’ll only use them within the hash, therefore I’ll use lambdas.

Leave a Comment