Python Range() Function

In python, range() function is useful to generate the sequence of numbers starting from 0 based on the specified values. For example, if you specify the range(5) it will generate the numbers starting 0 to 4.

Range() Function Syntax

The following is the syntax of defining the range() function in python.

 

range(start, stop, step) 

If you observe the above range() function syntax, we used three parameters to define the range function, and all those parameters should be integers.

 

  • start - It's optional and useful to specify the starting position. In case if this value is not specified, by default, it will consider 0.
  • stop - It's required and useful to specify the ending position to stop generating the numbers.
  • step - It's optional and useful to specify the incrementation. By default, it's 1.

Range() Function Example

The following is the example of using the range() function in python to generate the sequence of numbers.

 

#starting from 0 to 3
print("----0 to 3----")
a = range(4) for x in a:
    print(x)
#starting from 2 to 5
print("----2 to 5----")
b = range(2,6)
for y in b:
    print(y)
#starting from 5 to 14, but increment 3 instead of 1
print("----5 to 14, Increment 3----")
c = range(5, 15, 3)
for z in c:
    print(z)

If you observe the above example, we used different arguments in the range() function to generate the sequence of numbers based on our requirements.

 

When you execute the above python example, you will get the result as shown below.

 

----0 to 3----
0
1
2
3
----2 to 5----
2
3
4
5
----5 to 14, Increment 3----
5
8
11
14

This is how you can use the range() function in your program to generate the sequence numbers based on your requirements.