transformation
sum()
Sums the items of an iterable, adding them to start. Optimized for numbers.
sum(iterable, /, start=0) Parameters
| Parameter | Purpose |
|---|---|
| iterable | Iterable of addable values |
| start | Initial value (default 0) |
Examples
sum([1, 2, 3]) Returns 6
sum([1.5, 2.5], start=10) Returns 14.0
sum(x*x for x in range(5)) Returns 30 (0+1+4+9+16)
Gotcha
Refuses to sum strings (use ''.join instead). For floats, math.fsum() is more accurate.
Related built-ins
min()
Returns the smallest item in an iterable or the smallest of two or more arguments. Supports a key function for custom comparison.
max()
Returns the largest item in an iterable or the largest of two or more arguments. Supports a key function for custom comparison.
any()
Returns True if any element of the iterable is truthy. Short-circuits on the first truthy value.
sorted()
Returns a new sorted list from any iterable. Uses Timsort — stable, O(n log n).
all()
Returns True if every element of the iterable is truthy (or if the iterable is empty). Short-circuits on the first falsy value.