Contents
Python – sum()
Python sum() builtin function returns the sum of elements in the given iterable.
Syntax
The syntax of sum()
function is
sum(iterable, start=0)
where
iterable
is any iterable like list, tuple, etc., usually with numbers.start
is the initial value in the sum, before accumulating the items of the iterable.
Examples
1. Sum of items in a list
In the following program, we take a list of numbers in nums
, and find their sum using sum() function.
Python Program
nums = [2, 8, 1, 6]
result = sum(nums)
print(result)
Run Output
17
2. Sum of items in a tuple
In the following program, we take a tuple with numbers in myTuple
, and find their sum using sum() function.
Python Program
myTuple = (2, 8, 4, 0)
result = sum(myTuple)
print(result)
Run Output
17
3. Sum of items with a specific start
In the following program, we take a list of numbers in nums
, and find their sum using sum() function, with a specific start
of 100.
Python Program
nums = [2, 8, 1, 6]
result = sum(nums, start = 100)
print(result)
Run Output
117
Summary
In this tutorial of Python Examples, we learned the syntax of sum() function, and how to find the sum of items in the given iterable using sum() function with examples.