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) print(and)
square = lambda x: x*x ans = square(5) print(and)
Both print the same result. However, the lambda expression looks cleaner.
add = lambda x,y: x+y print(add(5,4))
pairs = [(1,2) , (3,14) , (5,26) , (10,20) ] sorted_pairs = sorted(pairs, key = lambda pair: max(pair,pair)) 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.
func = lambda : return "String" print(func())
print( (lambda x,y: x+y)(4,5))