Python sum()
Python sum() builtin function is used to find the sum of elements in an iterable with a given start.
In this tutorial, we will learn about the syntax of Python sum() function, and learn how to use this function with the help of examples.
Syntax
The syntax of sum() function is
sum(iterable, start=0)
where
Parameter | Required/Optional | Description |
---|---|---|
iterable | Required | A python iterable object. |
start | Optional | Starting value for the sum. |
If start is specified, sum() function starts adding up the elements with an initial value of start.
sum(iterable, start) = start + sum(iterable)
Returns
The function returns the resulting sum of start and items in iterable.
Examples
1. Sum of items in list
In this example, we will take an iterable, say a list of numbers, and find their sum using sum() function.
Pass the list myList
as argument to sum() function. The function shall return the sum of elements in this list.
Python Program
myList = [2, 0, 8, 6]
result = sum(myList)
print(result)
Output
16
2. sum() with start
In this example, we will pass a value for start parameter to sum() function.
Pass the list myList
as argument to sum() function and give start as 10
. The function shall return the sum of start and elements in this list.
Python Program
myList = [2, 0, 8, 6]
start = 10
result = sum(myList, start)
print(result)
Output
26
Conclusion
In this Python Tutorial, we have learnt the syntax of Python sum() builtin function, and also learned how to use this function, with the help of Python example programs.