range( ) function in Python

In the previous article we explored while loops, now we will look at the purpose of the range ( ) function. The range ( ) function is used to generate a specified range of numbers. There are three forms of range functions, and we will explore each one. Suppose we specify a range(5), the number range taken by the program is from 0 to 4. The number series generated by the range function is it’s own unique data type. However it can be converted to other data types such as lists.

Utilizing range( ) function in Python

Let us define a range of 5.

r=range(5)
print(r)
Output:
range(0, 5)

We see that it only returns the starting and end numbers for the variable defined. To utilize the range( ) function further we can convert it into other data types such as lists.

r=range(5)
print(r)
l=list(r)
print(l)
Output:
range(0, 5)
[0, 1, 2, 3, 4]

The code returns the range numbers as a list along with it’s various elements. The range function always returns a value lesser than the end number. If we define a range x, we get the values from 0 to x-1. As said earlier, the range values returned belong to their own unique data type which is not used or seen in other Python operations. To demonstrate, let us use the type ( ) function.

r=range(5)
print(type(r))
Output:
<class 'range'>

Rather than specifying only a single parameter or value within the range function like we have done so far in this article, it also allows us to specify more parameters.

r=range(10, 20)
l= list(r)
print(l)
Output:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

It can also accept integer ranges, such as negative numbers.

r=range(-2,2)
l=list(r)
print(l)
Output:
[-2, -1, 0, 1]

When three parameter values are specified in the range function, the third value is taken as the step for each successive number to skip by while progressing through the range of values. For example:

r=range(10,20,2)
l=list(r)
print(l)
Output:
[10, 12, 14, 16, 18]

Suppose the third parameter or step value is negative, and the first parameter value is larger than the second. In such a case, the range is reversed.

r =range(20,10, -2)
l=list(r)
print(l)
Output:
[20, 18, 16, 14, 12]

Thus, we have seen the utility of the range( ) function and the three parameter modes in which it can be used. In the next article we will look at the For loop( ) statement in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *