The sum() in Python is a built-in function that calculates the sum of all elements in an iterable, such as a list, tuple, or set. The elements of the iterable must be numbers (e.g., integers or floats).
The sum() function has an optional second argument that can be used to specify a starting value for the sum. By default, the starting value is 0.
Syntax
sum(iterable, start)
Arguments
The sum() function adds the start and elements of the given iterators from left to right.
The iterable may be a list, tuple, set, or dictionary.
Example
You need to define the List and pass the List as a parameter to the sum() function, and you will get the sum of list items in return.
listA = [
11,
18,
19,
21,
46
]
print(sum(listA))
Output
115
To add floating-point numbers with exact precision, you can use math.fsum(iterable) instead, if you want to concatenate the items of a given iterable (items must be a string), then you can use the String join() method.
Example 2
The sum() function takes the second parameter, “start,” as an optional.
It returns this: sum of all elements + “start”.
listA = [
11,
18,
19,
21,
46
]
print(sum(listA, 19))
See the output.
134
That means 115 + 19 = 134.
That’s it.