A lambda function is a small anonymous function which returns an object.
The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions.
Instead of the conventional def
keyword used for creating functions, a lambda function is defined by using the lambda
keyword. The structure of lambda can be seen below:
Here are a few examples of lambdas in action:
# A squaring lambda functionsquare = lambda n : n*nnum = square(5)print num
# A subtraction lambda function with multiple argumentssub = lambda x, y : x-yprint(sub(5, 3))
A lambda is much more readable than a full function since it can be written in-line. Hence, it is a good practice to use lambdas when the function expression is small.
The beauty of lambda functions lies in the fact that they return function objects. This makes them helpful when used with functions like map
or filter
which require function objects as arguments.
A lambda makes the map
function more concise.
myList = [10, 25, 17, 9, 30, -5]# Double the value of each elementmyList2 = map(lambda n : n*2, myList)print myList2
Similar to map
, lambdas can also simplify the filter
function.
myList = [10, 25, 17, 9, 30, -5]# Filters the elements which are not multiples of 5myList2 = filter(lambda n : n%5 == 0, myList)print myList2