reduce() in Python

The reduce(fun,seq) applies a specific function to all of the list components mentioned in the sequence handed along. The “functools” module contains the definition for this function. To reduce the list on a single value, the reduce() function applies the fn function with two arguments cumulatively to the list items, from left to right. reduce(), unlike the map() and filter() procedures, is not a Python built-in function. The reduce() function belongs to the functools package. To utilize the reduction() function, add the following statement to the head of the program to import it from the functools module:

reduce() in Python

from functools import reduce
functools.reduce(myfunction, iterable, initializer)

The argument function is applied cumulatively to arguments in the list from left to right. The first parameter is the result of the function in the first call, and the third item in the list is the second. This process is continued until all of the items on the list have been checked off.

Working conditions:

  • The first two elements of the sequence are chosen in the first step, and the result is achieved.
  • The result is then saved after applying the same function to the previously obtained result and the number preceding the second element.
  • This method is repeated until there are no more elements in the container.
  • The final result is returned to the console and printed.
# python code to demonstrate the working of reduce()

# importing functools for reduce()
import functools

# initializing list
new_list = [11, 13, 15, 16, 12, ]

# reduce is applicable in computing a lists' sum
print("The  list's element sum is : ", end="")
print(functools.reduce(lambda x, y: x+y, 
new_list))

# using reduce to compute the lists' maximum element
print("The lists' maximum element is : ", end="")
print(functools.reduce(lambda x, y: x if x > y else y, new_list))
reduce() in action
reduce() in action

Making use of Operator Functions

Reduce() can also be used in conjunction with operator functions to achieve comparable functionality to lambda functions while improving readability.

# python code to demonstrate the working of reduce()
# using operator functions

# importing functools for reduce()
import functools

# importing operator for operator functions
import operator

# initializing list
new_list = [11, 13, 15, 16, 12, ]

# reduce() is useful in computing the lists' sum
# using operator functions
print("The lists' sum  of elements is : ", end="")
print(functools.reduce(operator.add, 
new_list))

# product computation using reduce 
# through operator functions
print("The lists'  elements product : ", end="")
print(functools.reduce(operator.mul, 
new_list))

# string concatenation using reduce
print("The concatenated product is : ", end="")
print(functools.reduce(operator.add, ["codeunderscored", "for", "codeunderscored"]))

accumulate() vs reduce()

The summation of a sequence’s elements can be calculated using both reduce() and accumulate(). However, the practical components of both of these are different.

The reduce() and accumulate() functions are defined in the “functools” and “itertools” modules, respectively.

reduce() keeps track of the intermediate result and only returns the summing value at the end. accumulate(), on the other hand, returns an iterator containing the intermediate results. The summation value of the list is the last integer returned by the iterator.
reduce(fun,seq) takes a function as the first parameter and sequence as the second. On the other hand, accumulate(seq, fun) accepts sequence as the first parameter and function as the second.

# python code to demonstrate summation
# using reduce() and accumulate()

# importing itertools for accumulate()
import itertools

# importing functools for reduce()
import functools

# initializing list
new_list = [11, 13, 14, 20, 14]

#accumulate() can help in printing summation
print("The lists' summation by using accumulate is :", end="")
print(list(itertools.accumulate(new_list, lambda x, y: x+y)))

# summation printing by use of reduce()
print("List summation  in reduce is as follows :", end="")
print(functools.reduce(lambda x, y: x+y, new_list))
accumulate() vs reduce()
accumulate() vs reduce()

reduce() as a three-parameter function

In Python 3, the reduction function, i.e., reduce(), works with three parameters or two. To put it another way, if the third parameter is present, reduce() inserts it before the value of the second one. As a result, if the second argument is an empty sequence, the third argument becomes the default.

Python program to illustrate the two number summation

def twoNumberSummation(function, iterable, initial_val=None):
	it = iter(iterable)
	if initial_val is None:
		value = next(it)
	else:
		value = initial_val
	for e in it:
		value = function(value, e)
	return value

# Note that the initial_val, when not None, is used as the first value instead of the first value 
# from iterable and after the whole iterable.
tuple_contents = (7,6,5,7,7,5,5,7)
print(twoNumberSummation(lambda x, y: x+y, tuple_contents,6))
two number summation
two number summation

Reducing a List

You may want to reduce a list to a single value on occasion. Consider the following scenario: you have a list of numbers:

student_scores = [75, 65, 80, 95, 50]

A for loop can also come in handy in calculating the sum of all elements in the scores list:

student_scores = [75, 65, 80, 95, 50]

total = 0

for score in student_scores:
  total += score
print(total)

In this case, we’ve condensed the entire list to a single value, which is the sum of all of the list’s members. The example demonstrates how to use the reduce() function to calculate the sum of the scores list’s elements.

from functools import reduce

def sumVals(x, y):
  print(f"x={x}, y={y}, {x} + {y} ={x+y}")
  return x + y

result_vals = [75, 65, 80, 95, 50]
final_total = reduce(sumVals, result_vals)
print(final_total)
sum of the scores
the sum of the scores

The reduce() function, as you can see from the output, gradually adds two components of the list from left to right and reduces the entire list to a single value. Instead of creating the sumVals() function, you can use a lambda expression to make the code more concise:

from functools import reduce

scores = [75, 65, 80, 95, 50]

total = reduce(lambda a, b: a + b, scores)

print(total)

reduce() example

The mult() function returns the product of two numbers in the example below. This function is used with a range of numbers between 1 and 4, which are 1,2, and 3, in the reduce() function. The result is a 3 factorial value.

import functools
def mult(x,y):
  print("x=",x," y=",y)
  return x*y

fact=functools.reduce(mult, range(1, 4))
print ('Factorial of 3: ', fact)
reduce() example
reduce() example

Conclusion

The functools module contains the reduce() method. The reduce() function, like the map and filter methods, takes two arguments: a function and an iterable. However, it does not return another iterable but rather a single value. reduce() is a Python function that reduces the size of a string. In addition, reduce() is a Python method that condenses a list into a smaller number of items. The reduce() function has the following syntax: reduce(fn,list)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *