The sum() function in Python is used to add up numbers from any iterable such as a list, tuple, set, or dictionary values. It provides a clean and efficient way to calculate totals without writing loops manually.
Example:
Input: [1, 5, 2]
Output: 8
Syntax
sum(iterable, start)
Parameters:
- iterable: A sequence containing numbers (list, tuple, set, dictionary values).
- start(optional): A value added to the final sum. Default is 0.
Examples
Example 1: This example shows how to use sum() on a list to calculate the total of its elements.
Python
nums = [5, 10, 15]
res = sum(nums)
print(res)
Example 2: This example demonstrates using the optional start parameter to add a base value to the final sum.
Python
nums = [4, 6, 10]
res = sum(nums, 5)
print(res)
Example 3: This example shows how the sum() function works with different iterable types like dictionary values, sets, and tuples.
Python
# dictionary
d = {'a': 10, 'b': 20, 'c': 30}
print(sum(d.values()))
# set
s = {1, 2, 3, 4, 5}
print(sum(s))
# tuple
t = (1, 2, 3, 4, 5)
print(sum(t))
Explanation:
- sum(d.values()): accesses dictionary values (10, 20, 30) and adds them.
- sum(s): totals the set elements 1+2+3+4+5.
- sum(t): totals the tuple elements 1+2+3+4+5.
Summing Values Using For Loop
A for loop can be used to add elements of a list one by one. This method shows how summation works step-by-step and is useful when you need full control over how each value is processed during the calculation.
Python
nums = [10, 20, 30, 40, 50]
res = 0
for n in nums:
res += n
print(res)
Handling Errors When Using sum()
The sum() function requires numeric values. If the iterable contains incompatible types such as strings, Python raises a TypeError. This happens because addition cannot be performed between an integer and a non-numeric value.
Python
arr = ["a"]
print(sum(arr))
print(sum(arr, 10))
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Explanation:
- sum(arr) attempts to add "a" to 0, which is invalid.
- sum(arr, 10) attempts to add "a" to 10, causing the same error.
Calculating an Average
A common use of sum() is computing averages. We first calculate the total using sum() and then divide it by the number of elements.
Python
nums = [1, 2, 3, 4, 5, 1, 4, 5]
avg = sum(nums) / len(nums)
print(avg)
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice