The range Function in Python: Description and Examples
The range function returns a sequence of numbers within a specified range with a defined step. These sequences are typically used in for loops to iterate over numbers.
Syntax and Parameters
range(stop)
range(start, stop, step=1)
start— starting value of the sequence (default is 0).stop— end value of the sequence (not included).step— step of the sequence (default is 1).
Passing a single argument means you’re providing the stop value, not the start.
Usage Examples
In the example below, a sequence of numbers from 0 to 5 (excluding 5) is created. The for loop iterates over this sequence:
for i in range(5):
print(i)
0
1
2
3
4
To set the starting value, use two arguments:
for i in range(2, 5):
print(i)
2
3
4
Pass a third argument to specify the step:
for i in range(0, 10, 2):
print(i)
0
2
4
6
8
To create a sequence in reverse order, use a negative step. For example, a sequence from 5 to 1 can be created as follows:
for i in range(5, 0, -1):
print(i)
5
4
3
2
1
Indexing, Slices, and Conversion to a List
The range() function returns an iterable object that supports indexing and slicing:
numbers = range(10)
print(numbers) # range(0, 10)
print(numbers[2]) # 2
print(numbers[2:5]) # range(2, 5)
To get an actual list of numbers, use the list() function to convert the range object:
numbers = list(range(5))
print(numbers) # [0, 1, 2, 3, 4]
while and a Counter Variable or for and range?
To iterate over a sequence of numbers, use either a while loop with a counter variable or a for loop with range(). Using a for loop with range() is generally preferable as it makes the code more readable. Compare the example using a while loop and a counter variable with the example using a for loop and range():
# Using a while loop and a counter variable
i = 0
while i < 5:
print(i)
i += 1
# Using a for loop and range
for i in range(5):
print(i)