Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python sum() Function



The Pythonsum() function returns the sum of all numeric items in any iterable, such as alist ortuple. 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 thePython built-in functions.

Syntax

Following is the syntax for Pythonsum() function −

sum(iterable, start)

Parameters

The Pythonsum() function accepts the following parameters −

  • iterable − It represents an iterable with numeric operands.

  • start − It specifies the initial value of sum.

Return value

This function returns the sum of numeric operands in the iterable

sum() Function Examples

Practice the following examples to understand the use ofsuper() function in Python:

Example: Use of sum() Function

The 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 followingoutput

x: [10, 20, 30] sum(x): 60x: (10, -20, 10) sum(x): 0

Example: 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 = 5total = 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):  65

Example: Add Dictionary Values Using sum() Function

We can also usesum() function to add the values of adictionary. To do so, we need to pass the dictionaryvalues() 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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp