sum()

Adds together all the numbers in a collection.

Returns
The sum of the items.
On this page

Example

#
Python
scores = [72, 95, 88]
print(sum(scores))
print(sum(scores) / len(scores))

cart = [{"name": "HTML", "price": 49}, {"name": "Python", "price": 79}]
print(sum(item["price"] for item in cart))
Resultsaved result, you can check it
255
85.0
128

Definition and usage

#

The sum() function returns the sum of a collection's items. The second, optional argument, start, is the initial value added to, which defaults to 0.

It pairs nicely with generator expressions: sum(item["price"] for item in cart) totals a single field without building a helper list.

The function is not meant for joining strings. For that, use "".join(my_list). When summing many floating-point numbers, math.fsum() gives a more accurate result.

Syntax

#
Syntax
sum(iterable, start=0)

Parameters

#
  • iterable

    a collection of numbers

    The items to add up.
  • start

    number, default 0

    The starting value of the sum.

More examples

#
Counting how many conditions are true
Python
answers = [True, False, True, True]
print(sum(answers), "correct answers")
Resultsaved result, you can check it
3 correct answers

Good practices

#
  • The sum of boolean values is the count of true ones: sum(x > 50 for x in scores).
  • To join strings, use "".join(), not sum().

Related entries

#

Spotted a mistake or missing an example? Write to us.