The sum()
method in Python returns the sum of the iterable object inside it.
This method is declared as follows:
Two parameters can go inside the sum()
method:
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.
The return value of the sum()
method can be an integer or a floating-point number.
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 parametersx = (1, 2, 3, 4, 5)val = 10print sum(x, val)# Sum() method with the only mandatory parameterprint sum(x)