Python sum() Function
sum()is a built-in function in Python used to sum the elements in an iterable object.
sum()is one of the most commonly used mathematical functions in Python, which can quickly calculate the total sum of all elements in iterable objects such as lists, tuples, sets, etc.
Word Definition: summeans "summation", calculating the total of a series of numerical values.
Basic Syntax and Parameters
Syntax Format
sum(iterable, start)
Parameter Description
- Parameter iterable:
- Type: iterable object (list, tuple, set, etc.)
- Description: The iterable object to be summed.
- Parameter start(optional):
- Type: numeric value
- Description: Starting value, defaults to 0. This value will be added to the sum result.
Function Description
- Return value: Returns the sum result (integer or float).
- Requirements: The elements in the iterable object must be of numeric type (int, float).
Examples
Example 1: Basic Usage
Example
# Sum a list
numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print(result) # Output: 15
# Sum a tuple
result = sum((10, 20, 30))
print(result) # Output: 60
# Sum a set
result = sum({1, 2, 3})
print(result) # Output: 6
# Sum a range
result = sum(range(1, 101))
print(result) # Output: 5050 (sum of 1 to 100)
# Empty list
result = sum([])
print(result) # Output: 0
numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print(result) # Output: 15
# Sum a tuple
result = sum((10, 20, 30))
print(result) # Output: 60
# Sum a set
result = sum({1, 2, 3})
print(result) # Output: 6
# Sum a range
result = sum(range(1, 101))
print(result) # Output: 5050 (sum of 1 to 100)
# Empty list
result = sum([])
print(result) # Output: 0
Expected output:
15 60 6 5050 0
Code analysis:
- Supports various iterable objects such as lists, tuples, sets, range, etc.
- The sum of an empty iterable object defaults to 0.
Example 2: Using the start Parameter
Example
# Set the starting value
numbers = [1, 2, 3]
# Default start=0
result = sum(numbers)
print(result) # Output: 6
# Set start=10
result = sum(numbers, 10)
print(result) # Output: 16 (6 + 10)
# Negative starting value
result = sum(numbers, -10)
print(result) # Output: -4 (6 + -10)
# Useful when calculating cumulative sums
scores = [90, 85, 95]
bonus = 5
total = sum(scores, bonus)
print(total) # Output: 275 (90+85+95+5)
numbers = [1, 2, 3]
# Default start=0
result = sum(numbers)
print(result) # Output: 6
# Set start=10
result = sum(numbers, 10)
print(result) # Output: 16 (6 + 10)
# Negative starting value
result = sum(numbers, -10)
print(result) # Output: -4 (6 + -10)
# Useful when calculating cumulative sums
scores = [90, 85, 95]
bonus = 5
total = sum(scores, bonus)
print(total) # Output: 275 (90+85+95+5)
Expected output:
6 16 -4 275
Code analysis:
- The start parameter adds this value to the sum result.
- Often used to add a base score or bonus points to the total score.
Example 3: Practical Application
Example
# Calculate the average
numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print(f"Average: {average}") # Output: Average: 30.0
# Conditional summation
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Calculate the sum of even numbers
even_sum = sum(x for x in data if x % 2 == 0)
print(f"Sum of even numbers: {even_sum}") # Output: Sum of even numbers: 30
# Dictionary summation (sum of values)
prices = {'apple': 5, 'banana': 3, 'orange': 8}
total_price = sum(prices.values())
print(f"Total price: {total_price}") # Output: Total price: 16
# Calculate the sum of numbers divisible by 3 or 5 from 1 to 100
result = sum(x for x in range(1, 100) if x % 3 == 0 or x % 5 == 0)
print(result) # Output: 2318
numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print(f"Average: {average}") # Output: Average: 30.0
# Conditional summation
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Calculate the sum of even numbers
even_sum = sum(x for x in data if x % 2 == 0)
print(f"Sum of even numbers: {even_sum}") # Output: Sum of even numbers: 30
# Dictionary summation (sum of values)
prices = {'apple': 5, 'banana': 3, 'orange': 8}
total_price = sum(prices.values())
print(f"Total price: {total_price}") # Output: Total price: 16
# Calculate the sum of numbers divisible by 3 or 5 from 1 to 100
result = sum(x for x in range(1, 100) if x % 3 == 0 or x % 5 == 0)
print(result) # Output: 2318
Expected output:
平均值: 30.0 偶数之和: 30 Total: 16 2318
sum()is one of the most basic tools for processing numerical data, and can be combined with list comprehensions to achieve complex conditional summation.
Other Extensions
Python3 Built-in Functions