Python List Sum Syntax
Following is the syntax of the sum() method:
Where:
- iterable: the list where the elements of the iteration must be numbers
- start (optional): the initial value to add to the result. If not specified, the default is 0.
The following is an example of calculating the sum of the elements of a Python list:
How to add an initial value to the sum in Python?
The optional second argument of the sum() method is added to the total. It is useful when you already have a running total and want to continue adding to it.
How to sum a list of floats in Python?
The sum() method works with floats as well as integers. Because floating-point numbers are stored in binary, the result can carry a small rounding error, so the total is usually passed through the round() function before it is shown.
How to sum only some elements of a Python list?
To add up only the elements that meet a condition, pass a generator expression to sum() instead of the list itself. The expression is evaluated lazily, so no intermediate list is built.
Why does sum() raise a TypeError in Python?
The sum() method only adds numbers. Passing a list of strings raises a TypeError, because the starting value is the integer 0 and an integer cannot be added to a string. To join a list of strings, use the string.join() method instead.