Calculating Sum of Elements of Python List

To calculate the sum of the elements of a Python list, you can use the built-in sum(iterable, start) method. The sum() method takes an iteration as its first argument and an optional starting number as the second argument sums the items, and returns the result. The optional "start" argument adds the specified value to the result (defaults to 0). If the elements are not numbers, a TypeError exception will be thrown. In this Python Sum of List example, we calculate the sum of the list elements using the sum() method and add an initial value to the result, passing it as the second argument. Click Execute to run Python Calculate List Sum Example online and see the result.
Calculating Sum of Elements of Python List Execute
my_list = [1, 2, 3, 4, 5]

print(sum(my_list, 100))
Updated:

Python List Sum Syntax

Following is the syntax of the sum() method:

Python sum() Syntax
sum(iterable, start)

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:

Python List sum() Example
my_list = [1, 2, 3, 4, 5]

print(sum(my_list))

# output: 15

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.

Python sum() with Start Value Example
my_list = [1, 2, 3, 4, 5]

print(sum(my_list, 100))

# output: 115

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.

Python Sum of Floats Example
prices = [10.99, 5.49, 3.50]

print(sum(prices))
print(round(sum(prices), 2))

# output:
# 19.98
# 19.98

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.

Python Conditional Sum Example
numbers = [1, 2, 3, 4, 5, 6]

print(sum(n for n in numbers if n % 2 == 0))

# output: 12

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.

Python sum() TypeError Example
print(sum(["a", "b"]))

# TypeError: unsupported operand type(s) for +: 'int' and 'str'

print("".join(["a", "b"]))

# output: ab

See also