Python range() function

Updated on Jan 07, 2020


The range() function is used to generate a sequence of numbers over time. At its simplest, it accepts an integer and returns a range object (a type of iterable). In Python 2, the range() returns a list which is not very efficient to handle large data.

The syntax of the range() function is as follows:

Syntax:

range([start,] stop [, step]) -> range object
PARAMETER DESCRIPTION
start (optional) Starting point of the sequence. It defaults to 0.
stop (required) Endpoint of the sequence. This item will not be included in the sequence.
step (optional) Step size of the sequence. It defaults to 1.

Let's now look at a couple of examples to understand how range() works:

Example 1:

1
2
3
4
5
6
7
>>> 
>>> range(5)
range(0, 5)
>>> 
>>> list(range(5)) # list() call is not required in Python 2
[0, 1, 2, 3, 4]
>>>

Try it out:

print(range(5))

# list() call is not required in Python 2 
print(list(range(5))) 


When range() is called with a single argument it generates a sequence of numbers from 0 upto the argument specified (but not including it). That's why the number 5 is not included in the sequence.

Example 2:

1
2
3
4
5
6
7
>>>
>>> range(5, 10)
range(5, 10)
>>> 
>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>>

Try it out:

print(range(5, 10))

print(list(range(5, 10)))


Here range() is called with two arguments, 5 and 10. As a result, it will generate a sequence of numbers from 5 up to 10 (but not including 10).

You can also specify negative numbers:

1
2
3
4
5
6
7
>>> 
>>> list(range(-2, 2))
[-2, -1, 0, 1]
>>> 
>>> list(range(-100, -95))
[-100, -99, -98, -97, -96]
>>>

Try it out:

print(list(range(-2, 2)))

print(list(range(-100, -95)))


Example 3:

1
2
3
4
5
6
7
8
>>> 
>>> range(1, 20, 3)
range(1, 20, 3)
>>> 
>>> 
>>> list(range(1, 20, 3))
[1, 4, 7, 10, 13, 16, 19]
>>>

Try it out:

print( range(1, 20, 3))

print(list(range(1, 20, 3)))


Here the range() function is called with a step argument of 3, so it will return every third element from 1 to 20 (off course not including 20).

You can also use the step argument to count backwards.

1
2
3
4
5
6
7
>>> 
>>> list(range(20, 10, -1))
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11]
>>> 
>>> list(range(20, 10, -5))
[20, 15]
>>>

Try it out:

print(list(range(20, 10, -1)))

print(list(range(20, 10, -5)))


The range() function is commonly used with for loop to repeat an action certain number of times. For example, in the following listing, we use range() to execute the loop body 5 times.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> 
>>> for i in range(5):
...     print(i)
... 
0
1
2
3
4
>>>

Try it out:

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


This code is functionally equivalent to the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> 
>>> for i in [0, 1, 2, 3, 4]:
...     print(i)
... 
0
1
2
3
4
>>>

However, in the actual code, you should always use range() because it is concise, flexible and performs better.


Other Tutorials (Sponsors)