The sum() function in Python is a built-in function that calculates the sum of all the elements in an iterable. It takes an iterable as an argument and returns the sum of its elements. An iterable is any object that can be iterated over, such as lists, tuples, sets, dictionaries, and more.
Syntax
sum(iterable, start=0)
Parameters
- iterable : The iterable to be summed.
- start : The value to start the sum with. It is an optional parameter and its default value is 0.
Return Value
The sum() function returns the sum of all the elements in the iterable, starting with the value of the ‘start’ parameter.
Examples
Example 1: Calculating the sum of elements in a list
# Sum of elements in a list numbers = [1, 2, 3, 4, 5] print(sum(numbers))
Output
15
Example 2: Calculating the sum of elements in a tuple
# Sum of elements in a tuple numbers = (1, 2, 3, 4, 5) print(sum(numbers))
Output
15
Example 3: Using the ‘start’ parameter
# Using the 'start' parameter numbers = [1, 2, 3, 4, 5] print(sum(numbers, 10))
Output
25
Use Cases
- Calculating the total sum of elements in an iterable such as a list, tuple, set, etc.
- Calculating the sum of elements in a sequence such as a range.
- Calculating the sum of values in a dictionary, by using the values() method to return the values as a list.
In conclusion, the sum() function is a simple and efficient way to calculate the sum of elements in an iterable in Python. It is commonly used in a variety of use cases, such as calculating the total sum of elements in a list, tuple, set, or range, and even in dictionaries, by using the values() method to return the values as a list.