What is sum() in Python?

The sum() method in Python returns the sum of the iterable object inside it.

Syntax

This method is declared as follows:

The syntax of sum() method in Python

Parameters

Two parameters can go inside the sum() method:

  • an iterable object
  • an additive value

The iterable object can be a list or a tuple.

The additive value is an optional parameter that gets added to the final sum of the iterable object.

Return value

The return value of the sum() method can be an integer or a floating-point number.

Example

In the example below, x is a tuple of integers and val is the additive value. Since the additive value is an optional parameter, the sum() method can also be used without it.

In the second example, sum() only returns the sum of the integers inside x because it does not have the second optional argument in it.

# Sum() method with both parameters
x = (1, 2, 3, 4, 5)
val = 10
print sum(x, val)
# Sum() method with the only mandatory parameter
print sum(x)

Free Resources