reduce(function, iterable[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence or iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates (((
(function, sequence, initial=_initial_missing)
| 235 | _initial_missing = object() |
| 236 | |
| 237 | def reduce(function, sequence, initial=_initial_missing): |
| 238 | """ |
| 239 | reduce(function, iterable[, initial]) -> value |
| 240 | |
| 241 | Apply a function of two arguments cumulatively to the items of a sequence |
| 242 | or iterable, from left to right, so as to reduce the iterable to a single |
| 243 | value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates |
| 244 | ((((1+2)+3)+4)+5). If initial is present, it is placed before the items |
| 245 | of the iterable in the calculation, and serves as a default when the |
| 246 | iterable is empty. |
| 247 | """ |
| 248 | |
| 249 | it = iter(sequence) |
| 250 | |
| 251 | if initial is _initial_missing: |
| 252 | try: |
| 253 | value = next(it) |
| 254 | except StopIteration: |
| 255 | raise TypeError( |
| 256 | "reduce() of empty iterable with no initial value") from None |
| 257 | else: |
| 258 | value = initial |
| 259 | |
| 260 | for element in it: |
| 261 | value = function(value, element) |
| 262 | |
| 263 | return value |
| 264 | |
| 265 | try: |
| 266 | from _functools import reduce |
no test coverage detected