Python Lambda or Anonymous function

Python lambda functions is called as anonymous functions that can be defined without a name. Lambda function is used in single line expressions or used as argument to a function.

Lambda Syntax

1lambda arguments: expression

The arguments are the inputs that the function takes and the expression is the code that gets executed when the function is called.

lambda with single parameter

1multiply = lambda x : x * x 2 3result = multiply(2) 4print(result)

Output:

14

lambda with multiple parameter

code defines a lambda function that takes two parameters x and y and returns the product of the two numbers

1multiply = lambda x, y : x * y 2 3result = multiply(2, 3) 4print(result)

Output:

16

Lambda functions are often used as arguments to other functions, such as the map(), filter() and reduce() functions. These functions take a lambda function as their first argument and apply it to each item in an iterable.

lambda with map function

Following code uses the map() function to square each number in a list

1numbers = [1, 2, 3, 4, 5, 6] 2squared_numbers = map(lambda x: x**2, numbers) 3print(list(squared_numbers))

Output:

1[1, 4, 9, 16, 25, 36]

same logic without map and lambda function

1def makeSquare(k): 2 return k ** 2 3 4numbers = [1, 2, 3, 4, 5, 6] 5squared_numbers = [] 6 7for i in numbers: 8 squared_numbers.append(makeSquare(i)) 9 10print(squared_numbers)

lambda with filter function

filter is kind of a conditional statement, following code uses the filter() function to return only the even numbers in a list

1numbers = [1, 2, 3, 4, 5, 6] 2even_numbers = filter(lambda x: x % 2 == 0, numbers) 3print(list(even_numbers))

Output:

1[2, 4, 6]

same logic without filter and lambda function

1def makeFilter(k): 2 return k % 2 == 0 3 4numbers = [1, 2, 3, 4, 5, 6] 5even_numbers = [] 6 7for i in numbers: 8 if makeFilter(i): 9 even_numbers.append(i) 10 11print(even_numbers)

lambda with reduce function

Following code uses the reduce() function to sum all values in list

1from functools import reduce 2 3numbers = [1, 2, 3, 4, 5, 6] 4numbers_sum = reduce(lambda x, y: x+y, numbers) 5print(numbers_sum)

reduce will pass the return value from lambda to next iteration process to perform the operation until the end of list

Output:

121

same logic without reduce and lambda function

1numbers = [1, 2, 3, 4, 5, 6] 2count = 0 3for i in numbers: 4 count+=i 5print(count) 6 7# OR 8print(sum(numbers))