reduce(function, iterable, /[, initial]) -> value Apply a function of two arguments cumulatively to the items of an iterable, from left to right. This effectively reduces the iterable to a single value. If initial is present, it is placed before the items of the iterable in the c
(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 an iterable, from left to right. |
| 242 | |
| 243 | This effectively reduces the iterable to a single value. If initial is present, |
| 244 | it is placed before the items of the iterable in the calculation, and serves as |
| 245 | a default when the iterable is empty. |
| 246 | |
| 247 | For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) |
| 248 | calculates ((((1 + 2) + 3) + 4) + 5). |
| 249 | """ |
| 250 | |
| 251 | it = iter(sequence) |
| 252 | |
| 253 | if initial is _initial_missing: |
| 254 | try: |
| 255 | value = next(it) |
| 256 | except StopIteration: |
| 257 | raise TypeError( |
| 258 | "reduce() of empty iterable with no initial value") from None |
| 259 | else: |
| 260 | value = initial |
| 261 | |
| 262 | for element in it: |
| 263 | value = function(value, element) |
| 264 | |
| 265 | return value |
| 266 | |
| 267 | |
| 268 | ################################################################################ |