Understanding range() Function in Python with Examples
In python programming language, range()
is built-in function which is very handy to generate integer numbers and is frequently used to iterate through list
. Before diving into use case of this function we first understand what it does with examples.
First, let's look at its syntax:
range(stop) -> range object
# OR
range(start, stop) -> range object
# OR
range(start, stop, step) -> range object
In the above syntax, start
, stop
& step
are arguments to the range. And -> range object
indicates this function returns range object
finally.
Working of range() Function
range()
function returns an object that produces a sequence of integers from start
(inclusive) to stop
(exclusive) by given step
. range(p, q)
produces p, p+1, p+2, p+3,p+4 ..., q-1
.
start
defaults to 0, and stop
is omitted! range(5)
produces 0, 1, 2, 3,4
.
These are exactly the valid indices for a list of 5 elements. When step
is given, it specifies the increment (or decrement).
range() Examples
Example 1 (with stop only)
x = range(5)
x = list(x) # converting to list
print(x)
Output
[0, 1, 2, 3, 4]
Example 2 (with start and stop)
x = range(5,11)
x = list(x) # converting to list
print(x)
Output
[5, 6, 7, 8, 9, 10]
Example 3 (with start, stop and step)
x = range(7,34,3)
x = list(x) # converting to list
print(x)
Output
[7, 10, 13, 16, 19, 22, 25, 28, 31]
range() Function and for Loop Examples
First, let's run:
for i in range(5):
print(i)
Which gives:
0 1 2 3 4
In above program range(5)
generates number 0, 1, 2, 3, 4 and we iterate through them to print. In general when one argument say (p) is given to range function then it generates number from 0 to p-1 and each time updating value by 1.
Second, let's run:
for i in range(2,5):
print(i)
Which gives:
2 3 4
In above program range(2,5)
generates number 2, 3, 4 and we iterate through them to print. In general when two arguments say (p, q) are given to range function then it generates number from p to q-1 and each time updating value by 1.
Third, let's run:
for i in range(1,8,2):
print(i)
Which gives:
1 3 5 7
In above program range(1,8,2)
generates number 1, 3, 5, 7 and we iterate through them to print. In general when three arguments say (p, q, r) are given to range function then it generates number from p to q-1 with update value of r.
Finally Checking Type of Object Returned by range() Function
>>> x = range(5)
>>> type(x)
<class 'range'>