Python lambda functions

Lambda function are small one line function. Lambda function are also referred to as anonymous function as they don’t have function name associated with them. 

Syntax of lambda function:

lambda  arguments : expression

A lambda function can have any number of arguments but only one expression. This expression is often equivalent to return value in normal function.

Comparing lambda function with normal function

Let’s see a normal function

def add(x,y):
    return x+y

An equivalent lambda function for above function would be:

lambda x, y: x + y

Why use lambda function?

Lambda function are simple one line function which can return an expression based on the parameters. This makes it powerful to do computation , when we use it inside a function it can take additional parameter for calibration.

Example : Lambda function inside a return statement

def add_3_coordinates(x_cord):
    y_coord = 2
    return lambda z_coord: x_cord + y_coord + z_coord

result = add_3_coordinates(5)
final_result = result(6)
print("old sum =",final_result)

# we can simply do
print("new sum=",add_3_coordinates(5)(6))

Output

old sum = 13
new sum= 13

Example

add_coord = lambda x_coord, y_coord : x_coord + y_coord
print("add_coord(3,4)=", add_coord(3,4))

Output:

add_coord(3,4)= 7

Lambda function could be combined with  and  and  or  statement to get more complex statement. 

Example 3: Lambda function to find odd or even numberĀ 

odd_even = lambda x: (x % 2 and 'Yes' or 'No')

print("odd_even(4)=",odd_even(4))
print("odd_even(5)=",odd_even(5))

Output:

odd_even(4)= No
odd_even(5)= Yes

Leave a Reply

Your email address will not be published. Required fields are marked *