How to Sum Numbers in a Range in Python
Summing numbers within a range is a common operation in Python.
This guide explores various methods for calculating sums within a range, including basic summation, using a step value, summing integers from 1 to N using a formula, and summing numbers divisible by a specific value.
Summing Numbers in a Range with sum()
and range()
The range()
function creates a sequence of numbers, and you can use the sum()
function to add them together:
start = 1
stop = 5
total = sum(range(start, stop)) # (1 + 2 + 3 + 4)
print(total) # Output: 10
- The
range(start, stop)
creates an iterable sequence of integers fromstart
(inclusive) up to but not includingstop
. - The
sum()
function adds the values in the provided iterable and returns the result.
If you call range()
with only one parameter, it will be the stop value (exclusive). The start value will default to 0
and the step will default to 1
.
total = sum(range(5)) # (0+1+2+3+4)
print(total) # Output: 10
Summing Numbers in a Range with a Step
You can also specify a step value when generating a sequence with range using range(start, stop, step)
:
start = 1
stop = 5
step = 2
total = sum(range(start, stop, step)) # (1+3)
print(total) # Output: 4
print(list(range(start, stop, step))) # Output: [1, 3]
range(start, stop, step)
generates a sequence fromstart
(inclusive) up tostop
(exclusive), using an increment ofstep
.
Summing Integers from 1 to N
To sum integers from 1 to N, you can use a mathematical formula for efficiency: n * (n + 1) // 2
, where //
is the floor division operator.
n = 5
total = n * (n + 1) // 2
print(total) # Output: 15
n = 100
total = n * (n + 1) // 2
print(total) # Output: 5050
- This formula provides a much more efficient way to get the sum of integers from 1 to n.
- The
//
operator returns the integer value from a division, not the float.
Summing Numbers Divisible by N in a Range
To sum numbers in a range that are divisible by a specific value, create a range with a correct starting point and using a specific step value:
def sum_divisible_in_range(start, stop, divisor):
while start % divisor != 0:
start += 1
return sum(range(start, stop, divisor))
print(sum_divisible_in_range(1, 6, 2)) # Output: 6 (because sum is 2+4)
print(sum_divisible_in_range(1, 7, 3)) # Output: 9 (because sum is 3+6)
print(sum_divisible_in_range(1, 8, 4)) # Output: 4 (because sum is 4)
- First, a
while
loop increases thestart
value until it is divisible by thedivisor
. - Then it creates a range which starts from the computed
start
and it increases bydivisor
at each step.