import functools
#define a list
numbers = [4, 2, 1, 9, 6]
#get the sum of the list
total = functools.reduce(lambda x, y : x + y, numbers)
#print the result
print(total)
# -> 22
The reduce() method is used from functools module from python. It means if you want to use the reduce method, you will have to import functools first.
The basic syntax to use reduce method.
functools.reduce(function, sequence)
The reduce() method from functools takes two parameters. First argument is the function that ran on every iteration where it takes two parameters as previous value and item value. Second argument is the sequence e.g. list if items.
In the code example, we are calculating the sum of numbers list items.
We are using the lambda function in reduce() method but you can also use the python function in place of the lambda function.
The code example below is another example of getting the sum of list items. But we are using the python function in place of the lambda function here.
import functools
#define a list
numbers = [4, 2, 1, 9, 10]
#create method add
def add(x, y):
return x + y
#get the sum of the list
total = functools.reduce(add, numbers)
#print the result
print(total)
# -> 26
import functools
names = ["He", "ll", "o", "Wo", "rld"]
result = functools.reduce(lambda a, b : a + b, names)
print(result)
#-> 'HelloWorld'
0 Comments