Lambda Functions in Python

Learn to write and use lambda functions in Python.

Lambda Functions in Python

Ever heard of something called Anonymous functions? An anonymous function in Python is a function that is defined without a name.

While functions in Python are defined using the def keyword, anonymous functions are defined using the lambda keyword. Hence, they are also called lambda functions.

💡
Check out the YouTube video for Lambda functions by scrolling to the bottom or clicking this link!

Syntax of Lambda functions

lambda argument: expression

argument - The argument to pass into
           your lambda function 

Code

# Normal Function
def return_squared(x):
    return x**2

# Lambda Function
return_squared = lambda x : x**2

Notice, the absence of a function name in the Lambda function. Also, the def keyword is replaced with a lambda keyword.

lambda x: x**2 is the lambda function. Here x is the argument and x**2 is the expression that gets evaluated and returned as a function object.

It’s also easy to call lambda functions.

Here is the difference between a normal function in Python vs a Lambda function.

# Normal Function
def return_squared(x):
    return x**2

result = return_squared(5)
print(result)

# Lambda Function
return_squared = lambda x : x**2

result = return_squared(5)
print(result)

Output

25
25

Multiple arguments with lambda function

You can provide as many arguments you want with lambda function.

Code

addition = lambda x,y:x+y
print(addition(5,3))

Output

8

Advantages of Lambda functions

  1. Fewer Lines of Code.
  2. Can be easily used with filter, map and reduce methods.

Check out my YouTube video on lambda Function to get a better understanding of the concept.