What is a Python lambda function?

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:

svg viewer

Examples of simple lambdas

Here are a few examples of lambdas in action:

A squaring function

# A squaring lambda function
square = lambda n : n*n
num = square(5)
print num

A subtraction function

# A subtraction lambda function with multiple arguments
sub = lambda x, y : x-y
print(sub(5, 3))

The purpose of lambdas

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.

Map with lambda

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

Filter with lambda

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 5
myList2 = filter(lambda n : n%5 == 0, myList)
print myList2
Copyright ©2024 Educative, Inc. All rights reserved