Python range() function
In this tutorial, we are going to see the use of range() function in Python language.
The range() is a built-in function available in Python that is used for finding the range between the given integer limit.
Consider the below Example 1.
for i in range(10): print(i, end=', ')
output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
In the above program, the range is given as 10 in the for loop and thus it gives the output for the range of 0 to 9.
The value given inside the range will not be taken as a count (i.e) it takes from 0 and a total of 10 counts and thus 9.
Syntax for Python range() function
range ( Start value, End value, Step value)
In the syntax, it is noted that the step value is an optional one. It will have a default value of 1. The step value is generally used for the increment or decrement operation for the count.
The start value is used for mentioning the starting of the range.
The end value is used for mentioning the end of the range.
By default, it considers the start value is 0 and increment by 1 and goes up to the end value.
The Syntax can also contain only a single value as the end value to mark the end of the range as mention in the above example. (refer example1)
for i in range(1, 10, 2): print(i)
The above example in which the start value is assigned to 1, the end value is assigned to 10 and finally, the step value is assigned to 2. So it prints the number by difference 2 within the range 10.
The step value should not be given as 0. Because it will raise a ValueError exception.
range() inclusive in python
Generally, the range(n) is an exclusive nature.ie., it does not consider the last element mentioned inside the range in the output in order to add the last value just increment the end value by 1
for i in range(0,5+1): print(i,end=',')
In order to reverse the number inside the range is also possible in Python
for i in range(5,-1,-1): print(i,end=',')
Here the step value is assigned to -1 so our output will be in the reversed format.
converting a given range() in the form of a list
output: [0,1,2,3,4] consider the above example in which the keyword list is used to convert the output in the form of a list
concatenation of the two range()
from itertools import chain concatenated_range = chain(range(0,5+1), range(6,10+1)) for i in concatenated_range: print(i,end=", ")
Consider the above example in which in order to concatenate the two range() function we import chain() function from the itertools package.