Python Sum Function
What does sum() do?
The sum()
function adds up all the items in an iterable (like a list or tuple) and returns the total. You can also provide a starting value.
Basic Syntax
sum(iterable, /, start=0)
iterable
: The sequence of numbers to add.start
: (Optional) The value to start with (default is 0).
Examples with lists and tuples of numbers
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Output: 10
tuple_numbers = (5, 5, 5)
print(sum(tuple_numbers)) # Output: 15
Using the start parameter
numbers = [1, 2, 3]
print(sum(numbers, 10)) # Output: 16 (10 + 1 + 2 + 3)
Summing with different types (caution)
sum()
works with numbers (int, float, complex).- Do not use with non-numeric types (e.g., strings, lists) or mixed types.
# sum(["a", "b"]) # TypeError!
Summary
sum()
adds up all items in an iterable, starting fromstart
(default 0).- Works with numbers (int, float, complex).
- Returns the total sum.