python lambda functions

#Day12 – Anonymous Functions in Python

Posted by

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

variable(parameters)

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)

Lambda

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

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))

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)

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())

Lambda Function without variable name

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