The Python sum() function returns the sum of all numeric items in any iterable, such as a list or tuple. It also accepts an optional "start" argument which is 0 by default. If given, the numbers in the list are added to the start value. This function is one of the Python built-in functions.
SyntaxFollowing is the syntax for Python sum() function −
sum(iterable, start)Parameters
The Python sum() function accepts the following parameters −
iterable − It represents an iterable with numeric operands.
start − It specifies the initial value of sum.
This function returns the sum of numeric operands in the iterable
sum() Function ExamplesPractice the following examples to understand the use of super() function in Python:
Example: Use of sum() FunctionThe Python sum() function accepts iterables like lists and tuples as an argument and displays the result in corresponding iterable after adding their elements as shown in the below code.
x = [10,20,30] total = sum(x) print ("x: ",x, "sum(x): ", total) x = (10, -20, 10) total = sum(x) print ("x: ",x, "sum(x): ", total)
It will produce the following output −
x: [10, 20, 30] sum(x): 60 x: (10, -20, 10) sum(x): 0Example: sum() Function with Optional Parameter
The sum() function also accepts an optional argument, which is the starting value from which to begin the sum operation. In this example, we are passing the value of start as 5.
x = [10,20,30] start = 5 total = sum(x, start) print ("x: ",x, "start:", start, "sum(x, start): ", total)
On executing, the above code will produce the following output −
x: [10, 20, 30] start: 5 sum(x, start): 65Example: Add Dictionary Values Using sum() Function
We can also use sum() function to add the values of a dictionary. To do so, we need to pass the dictionary values() method as an argument to sum().
newDict = {"valOne": 101, "valTwo": 201, "valThree": 301} output = sum(newDict.values()) print("The sum of dictionary values:", output)
On executing the above code, it will produce the following result −
The sum of dictionary values: 603
python_built_in_functions.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4