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
- Other Related Concepts
Inclusive range PythonThe Python range function is commonly used to create a series of numbers. These numbers can be printed or used in loops.
Although the range in the code block says 0-4. The output is as follows.
for values in range(0,4): print(values)
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.
range(start, stop, Increment)
- 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:
This would print out values from 0 - 10.
for values in range(0,11): print(values)
Another method is to create a function which increments the range. This makes the Python range function inclusive. The code is as follows:
When the function is called, it adds 1 to the stop parameter. The output is as follows.
def range_inclusive(start, end): return range(start, end+1) range_inclusive(1, 10)
0 1 2 3 4 5 6 7 8 9 10