0
0
Pythonprogramming~5 mins

sum() function in Python

Choose your learning style9 modes available
Introduction

The sum() function adds up all numbers in a list or other group. It helps you quickly find the total without writing a loop.

You want to find the total cost of items in a shopping list.
You need to add up scores from a game to get the final result.
You want to calculate the total distance traveled from a list of daily distances.
You have a list of numbers and want to find their sum easily.
Syntax
Python
sum(iterable, start=0)

iterable is a group of numbers like a list or tuple.

start is optional and adds a number to the total at the beginning (default is 0).

Examples
Adds all numbers in the list: 1 + 2 + 3 + 4 = 10
Python
sum([1, 2, 3, 4])
Adds numbers in a tuple: 10 + 20 + 30 = 60
Python
sum((10, 20, 30))
Adds numbers in the list and then adds 10: (5 + 5 + 5) + 10 = 25
Python
sum([5, 5, 5], 10)
Sample Program

This program adds all numbers in the list numbers using sum(). It also shows how to add a starting value.

Python
numbers = [4, 7, 1, 3]
total = sum(numbers)
print(f"The total is {total}")

# Using start value
total_with_start = sum(numbers, 5)
print(f"Total with start value 5 is {total_with_start}")
OutputSuccess
Important Notes

sum() works only with numbers inside the iterable.

If the iterable is empty, sum() returns the start value (default 0).

Summary

sum() quickly adds all numbers in a list or tuple.

You can add a starting number to the total with the optional start argument.

It saves time and makes your code simpler than writing loops.