Python Range Function: Syntax
Python Range Function: Syntax
Syntax:
PARAMETER DESCRIPTION
stop (required) Endpoint of the sequence. This item will not be included in the sequence.
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
print(list(range(5)))
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
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).
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.