Python range() function
Updated on Nov 10, 2019
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
>>> range(5)
2
range(0, 5)
3
>>>
4
>>> list(range(5)) # list() call is not required in Python
5
2
6
[0, 1, 2, 3, 4]
7
>>>
Try it out:
1
print(range(5))
2
# 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 >>> range(5, 10)
3 range(5, 10)
4 >>>
5 >>> list(range(5, 10))
6 [5, 6, 7, 8, 9]
7 >>>
Try it out:
print(range(5, 10))
2
print(list(range(5, 10)))
4
Submit
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 >>> list(range(-2, 2))
3 [-2, -1, 0, 1]
4 >>>
5 >>> list(range(-100, -95))
6 [-100, -99, -98, -97, -96]
7 >>>
Try it out:
1
print(list(range(-2, 2)))
2
3
print(list(range(-100, -95)))
4
Submit
Example 3:
>>>
1
>>> range(1, 20, 3)
2
range(1, 20, 3)
3
>>>
4
>>>
5
>>> list(range(1, 20, 3))
6
[1, 4, 7, 10, 13, 16,
7
19]
8
>>>
Try it out:
1
print( range(1, 20, 3))
2
3
print(list(range(1, 20, 3)))
4
Submit
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 >>> list(range(20, 10, -1))
3 [20, 19, 18, 17, 16, 15, 14, 13, 12,
4 11]
5 >>>
6 >>> list(range(20, 10, -5))
[20, 15]
7
>>>
Try it out:
1
print(list(range(20, 10, -1)))
2
3
print(list(range(20, 10, -5)))
4
Submit
Output
Input
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 >>> for i in range(5):
3 ... print(i)
4 ...
50
61
72
83
94
10 >>>
Try it out:
1
for i in range(5):
2
print(i)
3
Submit
Output
Input
This code is functionally equivalent to the following:
>>>
1
>>> for i in [0, 1, 2, 3,
2
4]:
3
... print(i)
4
...
5
0
6
1
7
2
8
3
9
4
10
>>>
However, in the actual code, you should always use range() because it is concise,
flexible and performs better.