Python Reduce Function Tutorial (Simple Guide)

0
113
python reduce function

Python’s reduce function is a great tool to use when you have a sequence (e.g. list, tuples, etc) with multiple items and you have the objective of  returning only a single value.

This single value is achieved by combining the results of a function. Simple example are example:

  • conducting an operations  (e.g. summing or multiplying items with one another)
  • comparing the items against each other (e.g. max and min)

The reduce function takes the form:

reduce (function,sequence)

First let’s demo how it works for operations,  let’s say that you have a list:

l=[1,2,3,4,5,6,7,8,9,10]

and we have a function:

def sum(x,y):

return x+y

Using the reduce function will add up all the items so that a single value remains.

reduce(sum,l)

will output:

55

Most of the time the lambda expression is used for reduce  rather than defining a function first.

For example rather than defining sum first let’s use lambda directly.

reduce (lambda x,y: x+ y, l)

which will also output:

55

Using lambda in reduce just like in the map function has the purpose of saving time.

Next let’s demo reduce by comparing the items of a sequence.

Using the same list l:

reduce (lambda x,y: x if (x>y) else y, l)

will output the the highest item value in the list:

10

If we want to get the minimum then we need to run:

reduce (lambda x,y: x if (x<y) else y, l)

which will output the lowest value in the list:

1

The reduce function is usually used together with other functions like map and filter.

Now that you get the simple concept of the reduce function, go and challenge yourself by using it to find solutions to complex problems.

For more information go to the official python documentation:

https://docs.python.org/2/tutorial/datastructures.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here