PythonBuilt-in functions
sum()
Adds together all the numbers in a collection.
- Returns
- The sum of the items.
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
#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(), notsum().
Related entries
#- min()Returns the smallest item in a collection, or the smallest of several arguments.
- max()Returns the largest item in a collection, or the largest of several arguments.
- len()Returns the number of items in a collection, or the number of characters in a string.
- map()Calls a function for every item and returns an iterator of results.
Spotted a mistake or missing an example? Write to us.