Inclusive range Python - What does this signify?

In this short tutorial, we look at the inclusive range Python function. We explain what inclusive signifies with the help of examples.

Table of Contents - Inclusive range Python

  • Inclusive range Python
  • Code and Explanation
  • Closing thoughts - Inclusive range Python

Inclusive range Python

The Python range function is commonly used to create a series of numbers. These numbers can be printed or used in loops.

for  values in range(0,4):
    print(values) 
Although the range in the code block says 0-4. The output is as follows.
0
1
2
3

This is because Python prints values from 0 until 4. This behavior is called off-by-one and is common in programming languages. Essentially the function does not include the end value. This behavior is favorable while looping through objects since the index starts at 0. However, in case you are looking to print values or if you are new to Python, this can take some time to get used to.

While programming the best practice is to understand the language and use it to its strengths. Although I would recommend understanding and using the syntax as it is, there are a few methods to make range inclusive.

Code and Explanation:

Let us first take a look at the syntax of the range() function.

Syntax:

range(start, stop, Increment)

Parameters:

  1. Start - Optional, used to specify where the range should start. The default start value is 0.
  2. Stop - Required, used to specify where the range should stop.
  3. Increment - Optional, used to specify the incrementation.

The right way to print values from 0 to 10 would be as follows:
for  values in range(0,11):
    print(values) 

This would print out values from 0 - 10.

Another method is to create a function which increments the range. This makes the Python range function inclusive. The code is as follows:
def range_inclusive(start, end):
     return range(start, end+1)

range_inclusive(1, 10)

When the function is called, it adds 1 to the stop parameter. The output is as follows.

0
1
2
3
4
5
6
7
8
9
10

Closing thoughts - Inclusive range Python

Although the above method works properly it is not advisable to use it. I would only recommend using it for learning purposes. Product development would involve working with multiple developers and using such syntax would not be advisable.