Lambda Functions
Lambda functions are one-line, anonymous functions containing a single expression, which is evaluated when the function is called.
The actual lambda expression itself returns a function object, and can be passed as an argument to other functions, or assigned to a variable, just like any other function.
# lambda [parameters]: expression
add = lambda *x: sum(x)
print(add(4, 5, 10, 15))
This will display 34.
The function add() defined above is a variable which points to the otherwise anonymous function lambda *x: sum(x), which takes any number of arguments, and creates a list out of them within the function. The full syntax equivalent of this is:
def add(*x):
return sum(x)
Which is exactly the same, although it may not appear to be. The lambda function above is actually returning the results of sum(x) after evaluating it, but is doing so implicitly, whereas the full version explicitly returns sum(x).
It is also quite useful to pass lambda functions to map() and filter, as they take function objects as arguments and use them to perform calculations based on the provided functions. For a further explanation of these functions, see the Iterators section.
test_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda i: (i**2), test_list))
print(new_list)
While the actual usage of lambda is fairly limited, they can be used to avoid more potentially complicated syntax. Their main advantage is of course, that they can be placed in places that actual functions cannot be placed.
Theoretically, an entire program can be composed entirely of lambda functions, but that would likely be impractical given the wealth of other features provided by Python.