Rahul Banerjee

#Day12 - Anonymous  Functions in Python

#Day12 - Anonymous Functions in Python

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Today, we will be talking about anonymous functions in Python. Anonymous functions are also known as lambda functions. They are one-liners and look elegant. Below is the syntax

lambda parameters: expression

Since they have no names, they are called anonymous functions. However, to actually use them, we need to assign them to a variable

variable = lambda parameters: expression

To call a lambda function, we just call the variable and pass the parameters


Let's look at an example and compare a function written as a normal function and as a lambda function


def square(x):
    result = x*x
    return result

ans = square(5)


square = lambda x: x*x
ans = square(5)

Both print the same result. However, the lambda expression looks cleaner.

Lambda functions with multiple parameters

add = lambda x,y: x+y

Using lambda functions with the sorted function

pairs = [(1,2) , (3,14) , (5,26) , (10,20) ]

sorted_pairs = sorted(pairs, key = lambda pair: max(pair[0],pair[1]))

We have a list of tuples and want to sort it in ascending order based on the maximum number in the pair.

Parameterless lambda function

func = lambda : return "String"

Lambda Function without variable name

print( (lambda x,y: x+y)(4,5))


Share this