
What is a range function in Python?
Range is a built-in function in python which returns a series of integers. The range function takes three integer arguments – start, stop, step
Syntax of range function –
range(stop)
range(start,stop, step)
start – the starting number from which you want to generate the sequence of integers
stop – the integer before which you want to stop the sequence
step (optional) – The step size of the sequence. By default it is 1.
How to use Range Function in Python?
Let’s say that you want to generate a sequence of number from 0 to 20.
In [1]: for num in range(21):
...: print(num)
...:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
In [2]:
In range the start index is included and stop index is excluded. That is why we wrote range(21) for generating numbers from 0 to 20.
You can also write this code like this.
In [2]: for num in range(0,21):
...: print(num)
...:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
In [3]:
Here we explicitly tell python to start from 0 and go all the way up to 20.
The step argument helps you specify the size of step at each iteration of the loop. let’s say that you want to get only the even numbers between 0 to 20.
In [3]: for even_num in range(0,21,2):
...: print(even_num)
...:
0
2
4
6
8
10
12
14
16
18
20
In [4]:
You can also do negative stepping
In [6]: for num in range(20, -1, -2):
...: print(num)
...:
20
18
16
14
12
10
8
6
4
2
0
In [7]: