Python Range Function: An Introduction and Examples
The range function in Python is used to generate a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
The range function has the following syntax:
range(stop)
range(start, stop)
range(start, stop, step)stop: Required argument, an integer specifying the number to stop generating numbers.start: Optional argument, an integer specifying the number to start generating numbers. Default is 0.step: Optional argument, an integer specifying the number to increment between each number in the sequence. Default is 1.
The range function returns a sequence of numbers, which can be useful for looping or generating sequences of numbers, but it does not store all the values in memory, it generates them on the fly. To convert a range to a list, you can use the list function.
Example:
Get Hadi’s stories in your inbox
Join Medium for free to get updates from this writer.
Examples that demonstrate all three formats of the range function in Python:
- range(stop):
# Generates numbers from 0 to 4
for i in range(5):
print(i)Output:
0
1
2
3
42. range(start, stop):
# Generates numbers from 5 to 9
for i in range(5, 10):
print(i)Output:
5
6
7
8
93. range(start, stop, step):
# Generates numbers from 0 to 8 with step of 2
for i in range(0, 10, 2):
print(i)Output:
0
2
4
6
8





