The sum()
function adds up all the numbers in a list, tuple, or other iterable. It’s useful for mathematical calculations, data analysis, and aggregating values.
Example
numbers = [1, 2, 3, 4, 5]
print(sum(numbers))
Output:
15
Adds all numbers in the list.
Syntax
sum(iterable, start=0)
- iterable → A sequence (
list
,tuple
,set
,range
) of numbers. - start (optional) → A number to add to the sum (
default: 0
). - Returns → The total sum of all elements.
1. Summing a List of Numbers
nums = [10, 20, 30]
print(sum(nums))
# Output: 60
Adds all elements in the list.
2. Summing a Tuple
nums = (4, 5, 6)
print(sum(nums))
# Output: 15
Works the same way for tuples.
3. Using sum()
with a range()
print(sum(range(1, 6)))
# Output: 15 (1 + 2 + 3 + 4 + 5)
Efficiently adds up a sequence of numbers.
4. Using start
to Add an Extra Value
print(sum([1, 2, 3], 10))
# Output: 16 (1 + 2 + 3 + 10)
Adds an extra start
value before summing.
5. Summing Floating-Point Numbers
values = [1.5, 2.5, 3.0]
print(sum(values))
# Output: 7.0
Works with floating-point numbers too.
6. Summing a Set
numbers = {3, 6, 9}
print(sum(numbers))
# Output: 18
Works with sets as well.
7. Using sum()
on a List of Expressions
squared_numbers = [x**2 for x in range(1, 4)]
print(sum(squared_numbers))
# Output: 14 (1² + 2² + 3² = 1 + 4 + 9)
Allows custom calculations before summing.
8. Summing Values from a Dictionary
prices = {"apple": 2, "banana": 3, "cherry": 5}
print(sum(prices.values()))
# Output: 10
Use values()
to sum dictionary values.
9. Using sum()
with map()
numbers = ["1", "2", "3"]
print(sum(map(int, numbers)))
# Output: 6
Converts strings to integers before summing.
Key Notes
- ✔ Adds up numbers from a list, tuple, set, or range.
- ✔ Supports floating-point numbers.
- ✔ Works with dictionary values using
.values()
. - ✔ Use
sum(map(...))
for type conversion before summing.
By using sum()
, you can quickly compute totals, perform calculations on sequences, and analyze numerical data efficiently. 🚀