reduce(function, iterable[, initializer])
examples/advanced/reduce.py
#!/usr/bin/env python from __future__ import print_function numbers = [1, 2, 3, 4] print(reduce(lambda x,y: x+y, numbers)) # 10 = ((1+2)+3)+4 print(reduce(lambda x,y: x*y, numbers)) # 24 = ((1*2)*3)*4 print(reduce(lambda x,y: x/y, [8, 4, 2])) # ? print(reduce(lambda x,y: x+y, [2])) # print(reduce(lambda x,y: x+y, [])) # TypeError: reduce() of empty sequence with no initial value print(reduce(lambda x,y: x+y, [], 0)) print(reduce(lambda x,y: x+y, [2,4], 1)) # 7
The initializer is used as the 0th element returned by the iterable. It is mostly interesting in case the iterable is empty.