Lambda Functions¶
Let us get an overview of Lambda Functions in Python. They are also known as anonymous functions in other programming languages.
A lambda function is a function which does not have name associated with it.
It starts with the keyword
lambda
.Typically we have simple one liners as part of lambda functions.
There are restrictions while passing or creating lambda functions.
You cannot have return statement
Assignment operation is not allowed
Use lambda functions only when the functionality is simple and not used very often.
def my_sum(lb, ub, f):
total = 0
for i in range(lb, ub + 1):
total += f(i)
return total
def i(n): return n # typical function, for lambda def and function are replaced by keyword lambda
my_sum(5, 10, i)
my_sum(5, 10, lambda n: n)
my_sum(5, 10, lambda n: n * n)
my_sum(5, 10, lambda n: n * n * n)
def even(n): return n if n % 2 == 0 else 0 # Another example for typical function
my_sum(5, 10, even)
my_sum(5, 10, lambda n: n if n % 2 == 0 else 0)
my_sum(5, 10, lambda n: n if n % 3 == 0 else 0)