Skip to content

Lambda Expression in Python

lambda expression in python

Lambda expression in Python is a single line function. It can take any number of inputs but the output is always one. The lambda expression can be used without a name. lambda expression is often called lambda function, anonymous function (since it can be used without name).

Syntax of Lambda Expression in Python

lambda input1, input2, … : output

Lambda Expression in Python Examples

Example 1: Doubling a number using Lambda expression

#definning add function using lambda
add=lambda x:x+x

In the above code, a function add has been written using lambda expression, Where the function takes 5 as input and returns 5 + 5 = 10 as output.

Example 2: Lambda expression without any name

#using lambda function without any name
print((lambda x:x+x)(5))

The lambda expression mentioned in the previous code has been used in the above code without a name.

Use Lambda expression inside another function

We can also use lambda expression in any other function.

Example 1:

def double_sum(a,b,c):
    return lambda x:x*z
  • In the above code, lambda expression has been used in the double_sum function.
  • First double_sum(1,2,3) is executed which makes z = 6.
  • Then y(2) is executed which makes x = 2 and returns x * z = 2 * 6 = 12 as output.

Sort list using lambda expression

We can use lambda expression in key parameter of sort method while sorting any list.

Example 1:

students_roll.sort(key=lambda x:int(x[4:]))
['roll1', 'roll2', 'roll6', 'roll9', 'roll10', 'roll15']

While sorting the list given in the above code, we used lambda function in the key parameter of sort method.

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply