Python sum()

The sum() function adds the items of an iterable and returns the sum.

Example

marks = [65, 71, 68, 74, 61]

# find sum of all marks total_marks = sum(marks)
print(total_marks) # Output: 339

sum() Syntax

The syntax of the sum() function is:

sum(iterable, start)

The sum() function adds start and items of the given iterable from left to right.


sum() Parameters

  • iterable - iterable (list, tuple, dict, etc). The items of the iterable should be numbers.
  • start (optional) - this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted)

sum() Return Value

sum() returns the sum of start and items of the given iterable.


Example: Working of Python sum()

numbers = [2.5, 3, 4, -5]

# start parameter is not provided
numbers_sum = sum(numbers)
print(numbers_sum) # start = 10
numbers_sum = sum(numbers, 10)
print(numbers_sum)

Output

4.5
14.5

If you need to add floating-point numbers with exact precision, then you should use math.fsum(iterable) instead.

If you need to concatenate items of the given iterable (items must be strings), then you can use the join() method.

'string'.join(sequence)

Visit this page to learn about, Python join() Method

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to calculate the sum of all numbers in a list.

  • For example, for input [1, 2, 3, 4, 5], the output should be 15.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges