Login using Social Account
     Continue with GoogleLogin using your credentials
A lambda function is a small anonymous function and it is defined by the keyword "lambda".
A lambda function can take any number of arguments, but can only have one expression.
A lambda function is defined and used in the same statement.
Syntax:
lambda arguments : expression
Examples:
Increment a number by 1.
x = lambda a : a + 10
print(x(5))
Multiply two arguments return the result:
x = lambda a, b : a * b
print(x(3, 4))
The concept of lambda can be leveraged further by using this inside a normal function. In the below example, a generic function is created which acts a doubler, tripler or quadrupler or any multiplier.
def multiplier(n):
return lambda a : a * n
doubler = multiplier(2)
print(doubler(11))
tripler= multiplier(3)
print(tripler(11))
# or can do this directly
print(multiplier(4)(11))
You can also do operations like filter, map, etc using lambda which can also be using normal functions.
In the example below, we will filter the numbers divisible by 3 using different methods.
Method 1: Using a normal function
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
def filter_divisbile_by_n(n, numlist):
return [num for num in numlist if num%n==0]
divisible_by_3 = filter_divisbile_by_n(3, foo)
print("Method 1 output is:")
print(divisible_by_3, "\n")
Method 2: Using a function as an argument
def is_divisbile_by_n(n, num):
return num%n==0
def filter_divisbile_by_n(is_divisbile_by_n, n, numlist):
return [num for num in numlist if is_divisbile_by_n(n, num)]
divisible_by_3 = filter_divisbile_by_n(is_divisbile_by_n, 3, foo)
print("Method 2 output is:")
print(divisible_by_3, "\n")
Method 3: Using a lambda as an argument
def filter_divisbile_by_n(div_func, numlist):
return [num for num in numlist if div_func(num)]
divisible_by_3 = filter_divisbile_by_n(lambda x: x%3 == 0, foo)
print("Method 3 output is:")
print(divisible_by_3, "\n")
Method 4: Using a filter and normal function
def is_divisbile_by_3(num):
return num%3==0
divisible_by_3 = filter(is_divisbile_by_3, foo)
print("Method 4 output is:")
print(list(divisible_by_3),"\n")
Method 5: Using a filter and lambda function
divisible_by_3 = filter(lambda x: x%3 == 0, foo)
print("Method 5 output is:")
print(list(divisible_by_3),"\n")
Method 6: Using a lambda inside a function
def is_divisbile_by_n(n):
return lambda num: num%n == 0
divisible_by_3 = filter(is_divisbile_by_n(3), foo)
print("Method 6 output is:")
print(list(divisible_by_3),"\n")
Using lambda with map In the below example, we double the value of each element.
doubled_list = map(lambda x: x*2, foo) print(list(doubled_list))
Using lambda with reduce In the below example, we sum up all elements. from functools import reduce summed_list = reduce(lambda x, y: x + y, foo) print(summed_list)
Taking you to the next topic in seconds...
Want to create exercises like this yourself? Click here.
Loading comments...