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.
In [1]:
def my_sum(lb, ub, f):
total = 0
for i in range(lb, ub + 1):
total += f(i)
return total
In [2]:
def i(n): return n # typical function, for lambda def and function are replaced by keyword lambda
In [3]:
my_sum(5, 10, i)
Out[3]:
45
In [4]:
my_sum(5, 10, lambda n: n)
Out[4]:
45
In [5]:
my_sum(5, 10, lambda n: n * n)
Out[5]:
355
In [6]:
my_sum(5, 10, lambda n: n * n * n)
Out[6]:
2925
In [7]:
def even(n): return n if n % 2 == 0 else 0 # Another example for typical function
In [8]:
my_sum(5, 10, even)
Out[8]:
24
In [9]:
my_sum(5, 10, lambda n: n if n % 2 == 0 else 0)
Out[9]:
24
In [10]:
my_sum(5, 10, lambda n: n if n % 3 == 0 else 0)
Out[10]:
15