Python range() Function

FREE Online Courses: Transform Your Career – Enroll for Free!

Seeing the word ‘range’ you would remember values that lie in a particular interval. The function in Python has a similar function.

In this article, we will learn the range() function, its syntax along with examples. So, let us start.

What is Python range() function

The range() is a built-in function in Python that returns a range object based on the arguments given. The range is a data type in Python that is a sequence of immutable values.

The syntax of the range() function in Python is:

range(start,stop,step)

The first and the last parameters of the range() function are optional. The description of each of these parameters is as follows:

1. start: It is the first element from which the sequence starts. By default, the value of start is 0.

2. stop: This argument is compulsory and decides the number where the sequence should stop. The sequence will have the values till this number, executing this number.

3. step: This is the other optional argument that decides the increment from one value to the next one. By default, its value is 1.

Example of range() function in Python:

rng=range(4)
print("The type of ", rng,' is ', type(rng))

Output:

The type of range(0, 4) is <class ‘range’>

We can see that on printing the range(), we are not getting the values in the sequence enclosed in brackets as in the case of other containers. Instead, we are getting a range object and its type is range.

We will see the outputs of the range() function based on the number of parameters given to it.

One parameter

As discussed above the second parameter is mandatory when we use the range() function, we will first discuss this one. On giving the second argument as a number, say ‘n’, then we get a sequence containing values from 0 to ‘n-1’.

Example of range() function with one paramter:

list(range(6))

Output:

[0, 1, 2, 3, 4, 5]

Here we are converting the range object into a list because we can see the values in the sequence. We can observe that when we gave the input as 6, it gave all the integers from 0 to 5.

The input can also be negative. But we know that the increment by default is 1 and the start is 0. So, when we give a negative value as a stop since the stop is less than start we get an empty sequence.
Also when we give the input as zero, the value of ‘n-1’will be -1. For the same reason stated above, we get an empty list.

Example of Python range() function with negative paramter:

list(range(-3))

list(range(0))

Output:

[]

[]

However, the value cannot be a float value since the range() function does not support float-type values. We get an error as shown in the below example.

Example of getting an error on giving float values to the Python range() function:

list(range(4.9))

Output:

Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
list(range(4.9))
TypeError: ‘float’ object cannot be interpreted as an integer

Two Parameters

The two parameters are the start and the stop values. When we give the start as ‘m’ and stop as ‘n’, then we get a sequence of integers from ‘m’ to ‘n-1’.

Example of Python range() function with two paramters:

list(range(3,6))

list(range(9,2))

Output:

[3, 4, 5]

[]

In this example, we can see that we get the values starting from the start value, that is, 3. And end at stop-1, that is, 5. In the second sequence, the stop value 2 is less than 9 and the increment is 1. So, we get an empty sequence.

Here also, we can give either of the values as negative ones. But again, we get the sequence of values only if the stop is more than the start. Or else since the increment is 1, we get an empty sequence. The below example shows each of these cases.

Example of Python range() function with negative paramters:

list(range(-5,4))

list(range(2,-2))

list(range(-7,-1))

list(range(-4,-9))

Output:

[-5, -4, -3, -2, -1, 0, 1, 2, 3]

[]

[-7, -6, -5, -4, -3, -2]

[]

We can see in the first sequence that 4>-5. So, we got all the values from -5 to 3. And in the third case, -1>-7, and we got all the values from -7 to -1-1=-2. But in the second and the fourth case, the stop values are less than the start ones (-2<2 and -9<-4). So, we get empty lists.

Also if we give the same values for the start and the stop, there will be no values between them with increment 1. So, we get an empty sequence.

Example of range() function with same paramters:

list(range(1,1))

Output:

[]

We cannot give the values as float type data types as the range() does not support floats. We get an error on doing so as shown below.

Example of getting an error on giving float values to the range() function:

list(range(1,3.4))

Output:

Traceback (most recent call last):
File “<pyshell#25>”, line 1, in <module>
list(range(1,3.4))
TypeError: ‘float’ object cannot be interpreted as an integer

Three Parameters.

We can give three parameters, start, stop and step, to the range() function. If we give m,n,s as these values respectively. Then we get a sequence of values from m to n-1, with each value differing by the values.

Example of range() function with three paramters:

list(range(2,9,3))

Output:

[2, 5, 8]

As in the previous two cases, here also we can give a negative number to any of these three values. There are two things to be taken care of here:

1. If the step is positive, then the stop should be greater than the start to get a non-empty sequence. This is because the sequence is obtained by incrementing the values from the start by the step till the stop.

2. If the step is negative, the start will be decremented by the step till the stop occurs. So, the stop should be less than the start to not get an empty sequence.

Example of range() function with negative paramters:

list(range(3,-2,-1))

list(range(5,2,-2))

list(range(0,4,-3))

list(range(10,-2,3))

list(range(-4,10,2))

Output:

[3, 2, 1, 0, -1]

[5, 3]

[]

[]

[-4, -2, 0, 2, 4, 6, 8]

However, we cannot give the float values as the parameters. We get an error on doing so as the function does not support these values. Also, we cannot give the step as 0 because we cannot reach stop from the start using 0 as increment. We also get an error in this case.

Example of getting an error on giving float values to the range() function and on giving 0 as a step:

list(range(4,5,3.2))

list(range(2,2,0))

Output:

Traceback (most recent call last):
File “<pyshell#26>”, line 1, in <module>
list(range(4,5,3.2))
TypeError: ‘float’ object cannot be interpreted as an integer
Traceback (most recent call last):
File “<pyshell#27>”, line 1, in <module>
list(range(2,2,0))
ValueError: range() arg 3 must not be zero

Conversion to Other Data Types

In all the above examples, we have seen the conversion of the range() object to a list using the list() function. In addition, we can also convert it to other iterables like tuples and sets using the functions tuple() and set().

Example of converting the range() to other data types:

tuple(range(4,9))

set(range(-2,5,2))

Output:

(4, 5, 6, 7, 8)

{0, 2, 4, -2}

Operations on Python range objects

1. Accessing:

We can access using the index as we do with the lists and tuples. For example,

Example of accessing the values of range object:

rng=range(2,8)

list(rng)

rng[3]

rng[-1]

Output:

[2, 3, 4, 5, 6, 7]

5

7

2. Iteration:

We can iterate over the range object using the loops. It is widely used with the for loops. The below code gives an example,

Example of iterating over the range object:

for i in range(6):
    print(i)

Output:

0
1
2
3
4
5

3. Comparison:

We can compare two range objects using the relational operator ‘==’ and ‘!=’. We get the output as either True or False based on whether the condition for that operator is satisfied or not. For example,

Example of using comparison operators on the range objects:

range(3,7)==range(3,7)

range(1,5,2)!=range(1,5,3)

range(1,7)==range(1,7,2)

Output:

True

True

False

4. Membership:

We can use the membership operators ‘in’ and ‘not in’ to check if the value is present in the sequence or not. The ‘in’ operator returns True if the value exists in the sequence else it gives False. The ‘not in’ operator does the opposite to the ‘in’ operator.

Example of using membership operators on the range objects:

rng=range(2,10,2)

list(rng)

6 in rng

10 in rng

Output:

[2, 4, 6, 8]

True

False

5. Concatenation:

We can use the chain() function to concatenate the iterables, including the range. It adds the values of the second sequence at the end of the first one. To use this function, we have to import it from the itertools module.

Example of concatenation range objects:

from itertools import chain

rng=chain(range(-5,-1,2),range(5,10,2))

list(rng)

Output:

[-5, -3, 5, 7, 9]

Interview Questions on Python range() Function

1. Write a program to give a set of even numbers from 2 to 10.

Ans. We can give the start value as 2 and the stop as 11. This is because we also need 10 in the sequence. And to get even values, we can give the step as 2.

Example of getting even values from 2 to 10:

set(range(2,11,2))

Output:

{2, 4, 6, 8, 10}

Q2. Write a function to print the squares of numbers from 1 to 5 using a loop.

Ans. Below is the example of a program to get squares of numbers :

for i in range(1,6):
  print(i**2)

Output:

1
4
9
16
25

Q3. Write a function to print the characters of a string using the range() function.

Ans. We can use the len() function to know the stop point and strat will be the default value as the indexing in the string starts from 0.

Example of a iterating through a string :

string='PythonGeeks'
for i in range(len(string)):
    print(string[i])

Output:

P
y
t
h
o
n
G
e
e
k
s

Q4. Write a function to count the number of values that are divisible by 3 from 1 to 50.
Ans. We can give the start as 3, and the end as 50. As we need only those values divisible by 3, the step is 3. We can convert it to a list and find its length.

Example of finding the number of divisible below 50 :

list1=list(range(3,50,3))

list1

len(list1)

Output:

[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]

16

Q5. Write a function to get the values of a list and add only the positive values to the new list using the range() function.

Ans. Below is the Example of looping over a list:

list1=[3,-2,8,0,-5,4]

for i in range(len(list1)):
    if(list1[i]>0):
        list2.append(list1[i])

list2

Output:

[3, 8, 4]

Quiz on Python range()

Conclusion

In this article, we learned Python range() function, its parameters, and conversion to other data types. We also discussed the operations that we can do on the range objects. Finally, we saw some interview questions to practice.

Hope you enjoyed reading this article and learned something new. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

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