DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

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

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) 
Enter fullscreen mode Exit fullscreen mode

Although the range in the code block says 0-4. The output is as follows.

0
1
2
3
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • Start - Optional, used to specify where the range should start. The default start value is 0.
  • Stop - Required, used to specify where the range should stop.
  • 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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (1)

Collapse
 
kingbolumbu profile image
Kingbolumbu

Thanks for the blog. I have learned something new