Sum all numbers in a range in Python

avatar

Borislav Hadzhiev

Last updated: Jul 4, 2022

banner

Photo from Unsplash

Sum all numbers in a range in Python #

To sum all numbers in a range:

  1. Use the range() class to get a range of numbers.
  2. Pass the range object to the sum() function.
  3. The sum() function will return the sum of the integers in the range.
main.py
start = 1 stop = 5 # ✅ sum all integers in range() total = sum(range(start, stop)) print(total) # 👉️ 10 (1 + 2 + 3 + 4) # -------------------------------------- # ✅ sum all integers in range with step() step = 2 total_2 = sum(range(start, stop, step)) print(total_2) # 👉️ 4 (1 + 3)

We used the range() class to get a range of numbers.

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
# 👇️ [0, 1, 2, 3, 4] print(list(range(5))) total = sum(range(5)) print(total) # 👉️ 10
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1.

If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.

main.py
# 👇️ [1, 2, 3, 4] print(list(range(1, 5))) total = sum(range(1, 5)) print(total) # 👉️ 10

If the value for the stop parameter is lower than the value for the start parameter, the range will be empty.

main.py
# 👇️ [] print(list(range(5, 1))) total = sum(range(5, 1)) print(total) # 👉️ 0

The sum function can be used to calculate the sum of the numbers in the range.

The sum function takes an iterable, sums its items from left to right and returns the total.

The sum function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the start value and the items of the iterable. sum defaults to 0 (optional)

If you need to get a range with a step, pass a value for the third argument of the range() class.

main.py
start = 1 stop = 5 step = 2 total_2 = sum(range(start, stop, step)) print(total_2) # 👉️ 4 (1 + 3) # 👇️ [1, 3] print(list(range(start, stop, step)))

When the step argument is provided, the range will consist of every N numbers from start to stop.

The value for the step argument defaults to 1.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.