The sum()
function is a built-in function in Python that takes an iterable (such as a list) of numbers as input and returns the sum of all the numbers in the iterable.
Parameter Values
Parameter | Description |
---|---|
iterable | An iterable (list, tuple, set, etc.) of numeric values that will be summed up. |
start | An optional parameter that specifies the value to start the sum with. By default, it is 0. |
Return Values
The sum()
function in Python can return an int
, float
, or even complex
.
How to Use sum()
in Python
Example 1:
Return the sum of a 'list' or 'tuple' of numbers.
numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print(result)
Example 2:
Start the sum with an 'initial value'.
numbers = [1, 2, 3, 4, 5]
initial_value = 10
result = sum(numbers, initial_value)
print(result)
Example 3:
Calculate the sum of numbers in a 'generator expression'.
generator = (x**2 for x in range(5))
result = sum(generator)
print(result)