Using a for
loop with range()
, we can repeat an action a specific number of times
How to use range() function in Python
Python range()
function generates the immutable sequence of numbers starting from the given start integer to the stop integer. The range()
is a built-in function that returns a range object that consists series of integer numbers, which we can iterate using a for
loop. Below is the syntax of the range() function.
range(start, stop , [step])
it takes three arguments. Out of the three, two are optional. The start
and step
are optional arguments and the stop
is the mandatory argument.
Parameters
start
: (Lower limit) It is the starting position of the sequence. The default value is 0 if not specified. For example,range(0, 10)
. Here,start=0
andstop = 10
stop
: (Upper limit) generate numbers up to this number, i.e., An integer number specifying at which position to stop (upper limit). Therange()
never includes the stop number in its resultstep
: Specify the increment value. Each next number in the sequence is generated by adding the step value to a preceding number. The default value is 1 if not specified. It is nothing but a difference between each number in the result. For example,range(0, 6, 1)
. Here,step = 1
.
Return Value
It returns the object of class range
.
print(type(range(10)))
Steps to use range() function
The range()
function generates a sequence of integer numbers as per the argument passed. The below steps show how to use the range() function in Python.
- Pass start and stop values to range()
- Pass the step value to range()
- Use for loop to access each number
For example, range(0, 6)
. Here, start=0
and stop = 6
. It will generate integers starting from the start
number to stop -1
. i.e., [0, 1, 2, 3, 4, 5]
The step
Specify the increment. For example, range(0, 6, 2)
. Here, step = 2
. Result is [0, 2, 4]
Use for loop to iterate and access a sequence of numbers returned by a range()
.
