Python3 range() Function Usage
The Python3 range() function returns an iterable object (of type object), not a list type, so it doesn't print as a list when printed.
The Python3 list() function is an object iterator that can convert the iterable object returned by range() into a list, with the returned variable type being a list.
In Python2, the range() function returns a list.
Function Syntax
range(stop)
range(start, stop[, step])
Parameter Descriptions:
start: Counting starts from start. The default is 0. For example, range(5) is equivalent to
range(0, 5)
stop: Counting ends at stop, but does not include stop. For example: range(0, 5) is [0, 1, 2, 3, 4] without 5
step: The step size, defaulting to
1
. For example: range(0, 5) is equivalent to range(0, 5, 1)
Examples
If only the start and end values are provided, the step defaults to 1:
Example
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
If only one parameter is provided, it generates an integer sequence starting from 0, with the parameter being the end value, and the step defaults to 1:
Example
for number in range(6):
print(number)
Output:
0
1
2
3
4
5
You can specify a step to increment by different amounts each time:
Example
for number in range(1, 6, 2):
print(number)
Output:
1
3
5
Note: The end value 6 is not included.
Additionally, we can use negative numbers as the step to generate sequences in reverse from the end value:
Example
for number in range(6, 1, -1):
print(number)
Output:
6
5
4
3
2
Note: If using a negative number as the step, the start value must be greater than the end value.
If you only need to generate an integer sequence and do not need to iterate over it with a for loop, you can convert the return value of the range() function to a list or tuple, for example:
The following generates an integer list:
Example
>>> numbers = list(range(1, 6))
>>> numbers
[1, 2, 3, 4, 5]
The following generates an integer tuple:
Example
>>> numbers = tuple(range(1, 6))
>>> numbers
(1, 2, 3, 4, 5)