Summary: In this tutorial, we will learn what Lambda expression is and how can we convert a def function into a Lambda expression in Python.

What is Lambda Expression in Python?

Lambda Expression in Python which is also referred to as Lambda function is basically an anonymous function with a single Python expression as the body.

An anonymous function is a function that has no name and can be created without a def keyword.

Lambda expression like a normal standard Python function can accept any number of arguments but can only have a single expression as a function’s body.

A lambda expression begins with the lambda keyword followed by the arguments (optional) then followed by a colon (:) and finally ends with a single Python expression.

lambda arguments : python_expression

The lambda expression passes the arguments to the python_expression and returns the result after execution.

Let’s see some examples of Lambda expression for clear understanding.

Examples: Lambda Expression (Function)

Example 1: Lambda Function to check an Even number:

even = lambda n: n%2 == 0

print(even(6))  #outputs True

Example 2: Lambda Function to Grab first character of a String:

first = lambda s: s[0]

print(first('pencil'))    #outputs p

Example 3: Lambda Function to Reverse a string:

reverse = lambda s: s[::-1]

print(reverse('pencil'))   #outputs licnep

Example 4: Lambda Function to Add two numbers:

add = lambda x, y : x+y

print(add(4,6))     #outputs 10

How to convert an existing def Function into Lambda Function?

Since Lambda functions are short and concise, we may want to rewrite the existing normal standard Python function as a lambda function.

But the downside with the lambda functions is that they can only have a single expression in their body, hence we may not able to convert all functions written with def into a lambda expression.

However there is scope for many, let’s try converting the following function into a lambda expression:

def square(n):
    sqr = n**2
    return sqr

print(square(5))   #outputs 25

Step 1: Make function simple.

def square(n):
    return n**2

Step 2: Try to rewrite the whole function only using a single line (Although it is a bad practice).

def square(n): return n**2

Step 4: Remove def and rewrite in lambda.

lambda n: n**2

Step 5 (Final): Assign a label to it.

square = lambda n: n**2

print(square(5))    #outputs 25

Since lambda expressions are anonymous, it is important to label them to refer them later in the program.

I hope this has helped you to learn something about lambda function. If you have any doubts then comment below.

Leave a Reply