The reduce Function

reduce(func, s) collects data from a sequence and returns a single value

     a = [1,2,3,4,5,6]
     def sum(x,y):
         return x+y
     
     b = reduce(sum, a)   # b = (((((1+2)+3)+4)+5)+6) = 21 
  • Alternatively...
     b = reduce(lambda x,y: x+y, a)
  • The function given to reduce must accept two arguments and return a single result (suitable for reuse as one of the arguments).
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 87
July 17, 2000, beazley@cs.uchicago.edu
>>>