By Lenin Mishra
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
anonymous functions are defined using the lambda keyword.
Hence, they are also called lambda functions.
Syntax of Lambda functions
lambda argument: expression argument - The argument to pass into your lambda function
# 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.
def keyword is replaced with a
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.
# 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)
Multiple arguments with lambda function
You can provide as many arguments you want with lambda function.
addition = lambda x,y:x+y print(addition(5,3))
Advantages of Lambda functions
- Fewer Lines of Code.
- Can be easily used with
Build your foundation in Python with our self-paced Python Bootcamp for Beginners.