Python sum usage detailed explanation and examples
Python sum Usage Detailed Explanation and Examples
Python sum Syntax
Python’s sum()
function calculates the sum of a sequence. It accepts an iterable object (such as a list, tuple, set, or string) as an argument and returns the sum of all elements in the iterable.
The syntax is as follows:
sum(iterable, start=0)
iterable
: Required, represents the iterable object to be summed.start
: Optional, represents the starting value. When passed, the starting value is added to the sum of the iterable object.
Examples
Below are three examples using the sum()
function:
Example 1: Calculating the sum of the elements in a list
numbers = [10, 20, 30, 40, 50]
total = sum(numbers)
print(total) # Output is 150
In the above code, a list numbers
is first defined, then the sum()
function is used to calculate the sum of all elements in the list. Finally, the sum is printed.
Example 2: Calculating the Sum of Elements in a Tuple
marks = (85, 90, 95, 80)
total = sum(marks)
print(total) # Output: 350
In the above code, a tuple marks
is defined, and the sum()
function is used to calculate the sum of all elements in the tuple and print the result.
Example 3: Calculate the sum of numeric characters in a string
string = "Python123"
digits = [int(x) for x in string if x.isdigit()]
total = sum(digits)
print(total) # Output is 6
In the above code, a string string
is first defined. The list derivation digits = [int(x) for x in string if x.isdigit()]
is used to filter out the numeric characters and convert them to integers. The sum()
function is then used to calculate the sum of the numeric characters and print the result.