/    /  Python – Lambda Function

Python Functions with Lambda Function

In Python, Lambda function is a small anonymous function. Anonymous function means a function defined without a name. Lambda Functions are also called as Anonymous Functions. Lambda function can have variable number of arguments, but it contains only one expression.

Normal functions are defined by using def keyword. Whereas anonymous functions are defined by using the lambda keyword. Every anonymous function will have lambda keyword, parameters and function body.

Lambda function does not have return statement. We can use lambda function anywhere and also assigning of it to a variable is not required.  These functions can be used along with built-in functions like filter(), map() and reduce().

Syntax:

lambda arguments: expression

Example:

Using Lambda function, we will define a anonymous function of squaring a number.

Python Code:

x = lambda a : a * a
print(x(5))

Output:

25

Lambda function with filter()

filter() in lambda function takes in a function and list as arguments. This is the best way to filter out all elements of a sequence for which the functions return true.

Example

We will filter out all factors of 5 from the given list using filter() in lambda functions.

Python Code:

list = [5, 9, 25, 17, 34, 50, 62, 45, 56, 70, 87, 100] 
final_list = list(filter(lambda x: (x%5 == 0) , list)) 
print(final_list)

Output:

[5, 25, 50, 45, 70, 100]

Lambda function with map()

map() function in lambda function takes in function and list as an argument. It returns the new list which contains all lambda modified terms.

Example:

We will multiply 2 to all numbers in the given list by using map() function.

Python Code:

my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)

Output:

[2, 10, 8, 12, 16, 22, 6, 24]

Lambda Function with reduce()

reduce() function in lambda function takes in a function and list as an argument. New reduced list is returned by performing repetitive operation over the pairs of list. In order to use reduce(), we have to import functools in python.

Example:

By using reduce(), all the numbers in the list gets added and returns that number.

Python Code:

from functools import reduce
list = [1, 2, 3, 7, 8, 9] 
sum = reduce((lambda x, y: x + y), list) 
print (sum)

Output:

30