How to use lambda() Function with reduce() In Python
The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module.
A sum of all elements in a list using lambda and reduce() function
The code calculates the sum of elements in a list using the ‘reduce'
function from the ‘functools'
module. It imports ‘reduce'
, defines a list, applies a lambda function that adds two elements at a time, and prints the sum of all elements in the list. The output displays the computed sum.
Python3
from functools import reduce li = [ 5 , 8 , 10 , 20 , 50 , 100 ] sum = reduce (( lambda x, y: x + y), li) print ( sum ) |
Output:
193
Here the results of the previous two elements are added to the next element and this goes on till the end of the list like (((((5+8)+10)+20)+50)+100).
Find the maximum element in a list using lambda and reduce() function
The code uses the ‘functools'
module to find the maximum element in a list (‘lis'
) by employing the ‘reduce'
function and a lambda function. It then prints the maximum element, which is 6 in this case.
Python3
import functools lis = [ 1 , 3 , 5 , 6 , 2 , ] print ( "The maximum element of the list is : " , end = "") print (functools. reduce ( lambda a, b: a if a > b else b, lis)) |
Output:
The maximum element of the list is : 6
Python Lambda Functions
Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Contact Us