how to use "reduce" builtin function in python?

  • reduce is a built-in function in python module "__builtin__".
  • It takes function as first argument and second argument as an sequence of items.
  • It applies function on two arguments cumulatively to the items of a sequence from left to right and returns a single value.
  • If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
  • It doesn't allow empty sequence.
Let's see  examples

Let's sum all the elements in a list

traditional way


l = [1, 2, 3, 5, 6]
sum_of_numbers = 0
for num in l:
sum_of_numbers += num
print(sum_of_numbers)
# Output: 17

Let's do it using "reduce"

l = [1, 2, 3, 5, 6]

def sum_numbers(a, b):
return a + b

sum_of_numbers = reduce(sum_numbers, l)
print(sum_of_numbers)
# Output: 17

Let's find factorial of number 5

traditional way

num = 5
result = 1
for i in range(1, num+1):
result = result * i
print("Factorial of 5 = %s" % (result))
# Output: 120

Let's do it using "reduce"

num = 5
result = reduce(lambda x, y : x*y, range(1, num+1))
print("Factorial of 5 = %s" % (result))
# Output: 120

Let's find out max number in a list of numbers using "reduce" and "max"

l = [3, 1, 5, 10, 7, 6]
max_num = reduce(max, l)
print("max num = %s" % (max_num))
# Output: max num = 10

Buy a product to Support me