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.
The syntax of sum() function is
|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)
The function returns the resulting sum of start and items in iterable.
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.
myList = [2, 0, 8, 6] result = sum(myList) print(result)Try Online
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.
myList = [2, 0, 8, 6] start = 10 result = sum(myList, start) print(result)Try Online
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.