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 function square = lambda n : n*n num = square(5) print num
# A subtraction lambda function with multiple arguments sub = lambda x, y : x-y print(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
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 element myList2 = map(lambda n : n*2, myList) print myList2
map, lambdas can also simplify the
myList = [10, 25, 17, 9, 30, -5] # Filters the elements which are not multiples of 5 myList2 = filter(lambda n : n%5 == 0, myList) print myList2
View all Courses