Python sum Function with Examples

As indicated by its name, the Python sum function serves the purpose of calculating the total of numeric values contained within an iterable, such as a list.

Python sum Function Syntax

Example

sum(iterable, start)

Parameters

  • iterable: iterable can be list, tuples, and dictionaries, but an iterable object must contain numbers.
  • start: The start is added to the sum of numbers in the iterable. If start is not given in the syntax, it is assumed to be 0.
  • Different Examples for Python sum Function

Here are a few illustrations of the sum function provided below:

Python sum Function Example 1

This example shows sum of the list of numbers:

Example

s = sum([1, 2,2 ])

print(s)

s = sum([1, 2, 2], 10)

print(s)

Output:

Python sum Function Example 2

This example shows sum of floating point numbers:

Example

s = sum([2.5, 2.5, 3])

print(s)

Output:

Python sum Function Example 3

This example shows sum of complex numbers:

Example

s = sum([1 + 2j, 3 + 4j])

print(s)

s = sum([1 + 2j, 3 + 4j], 2 + 2j)

print(s)

s = sum([1 + 2j, 2, 1.5 - 2j])

print(s)

Output:

Output

(4+6j)

(6+8j)

(4.5+0j)

Input Required

This code uses input(). Please provide values below: