Search code snippets, questions, articles...

reduce() function in python

The reduce() function is used to reduce or summarise lists of data. It does this by taking a single argument which is an operation and then applying this repeatedly to all elements in a list.
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
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
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.

Example of reduce() 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'
In the above code snippet, we are joining all elements of a list named names using reduce() function.
Was this helpful?
0 Comments