Lambda Expressions in Python is one of the most useful tools which helps in creating an anonymous function.
Anonymous function in python is a function which has no name and can be created without a def keyword.
lambda: #single_statement
Function created using lambda expression works exactly same as that of a normal function using def but the only difference is that lambda’s body is a single expression, not a block of statements.
Basically, lambda’s body only contains what we return in def function body’s.
Let’s see what I am talking about by slowly converting a def function into a lambda function.
Converting def Function to Lambda Function in Python
def square(n): sqr = n**2 return sqr print(square(5))
Output
25
Making function simple.
def square(n): return n**2 print(square(5))
Output
25
Trying to write the whole function into a new line (Although it’s a bad practice).
def square(n): return n**2 print(square(5))
Output
25
Now we remove def and convert it into its lambda form.
lambda n: n**2
But it is an anonymous function and cannot be referenced so let’s assign a label to it.
square = lambda n: n**2 print(square(5))
Output
25
Python Lambda Examples
Example 1: Lambda Function to check an Even number.
even = lambda n: n%2 == 0 print(even(6))
Output
True
Example 2: Lambda Function to Grab first character of a String.
first = lambda s: s[0] print(first('pencil'))
Output
p
Example 3: Lambda Function to Reverse a string.
reverse = lambda s: s[::-1] print(reverse('pencil'))
Output
licnep
Example 4: Lambda Function to Add two numbers.
add= lambda x,y: x+y print(add(4,6))
Output
10
I hope this has helped you to learn something about lambda function. If you have any doubt then comment below.