The Sum() Built-in Function In Python

Function Name:

sum()

 

Function Signature:

sum(iterable[, start])

 

Function Overview:

Returns the sum of numbers present in an iterable.

 

The numbers could be any of the following types:

  • Integer
  • Floating-point number
  • Complex Number

 

Parameters:

iterable - The iterable whole elements to be summed

start       - This is an optional parameter.

       If specified, summing takes place only from the index specified by it. The start parameter has the default value of zero.

 

Example:

# Find sum of the elements - all integer tuple

primes = (2,3,5,7)

print("Sum of integers:{}".format(sum(primes)))

 

# Find sum of the floating point numbers

floats = (3.14, 6.28, 12.56)

print("Sum of floating point numbers:{}".format(sum(floats)))

 

# Find sum of the floating point numbers and integers

combi = (3.14, 6.28, 12.56, 1, 2)

print("Sum of floating point numbers and integers:{}".format(sum(combi)))

 

# Find sum of complex numbers

c1 = complex(-1.0, 0.0)

c2 = complex(-2.0, 0.0)

 

complexTuple = (c1, c2)

print("Sum of complex numbers:{}".format(sum(complexTuple)))

 

Output:

Sum of integers:17

Sum of floating point numbers:21.98

Sum of floating point numbers and integers:24.98

Sum of complex numbers:(-3+0j)


Copyright 2023 © pythontic.com