DEV Community

Cover image for #Day12 - Anonymous Functions in Python
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

#Day12 - Anonymous Functions in Python

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

variable(parameters)
Enter fullscreen mode Exit fullscreen mode

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

Normal

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

ans = square(5)
print(and)
Enter fullscreen mode Exit fullscreen mode

Lambda

square = lambda x: x*x
ans = square(5)
print(and)
Enter fullscreen mode Exit fullscreen mode

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

Lambda functions with multiple parameters

add = lambda x,y: x+y
print(add(5,4))
Enter fullscreen mode Exit fullscreen mode

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]))
print(sorted_pairs)
Enter fullscreen mode Exit fullscreen mode

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"
print(func())
Enter fullscreen mode Exit fullscreen mode

Lambda Function without variable name

print( (lambda x,y: x+y)(4,5))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)