Python3 range() function usage
Python3 range() function returns an iterable object (the type is object), not a list type, so it won't print a list when printed.
Python3 list() function is an object iterator that can convert the iterable object returned by range() into a list, and the returned variable type is a list.
Python2 range() functionReturns a list.
Function syntax
range(stop) range(start, stop[, step])
Parameter description:
- start: Counting starts from start. The default is to start from 0. For example, range(5) is equivalent torange(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: Step size, defaults to1. For example: range(0, 5) is equivalent to range(0, 5, 1)
Example
If only the start and end values are provided, the step size defaults to 1:
Example
print(number)
The output result is:
1 2 3 4 5
If only one parameter is provided, it generates a sequence of integers starting from 0, with the parameter as the end value and the step size defaulting to 1:
Example
print(number)
The output result is:
0 1 2 3 4 5
You can specify the step size to increment by different amounts each time:
Example
print(number)
The output result is:
1 3 5
Note: The end value 6 is not included.
Additionally, we can use a negative number as the step size to generate a sequence in reverse order from the end value:
Example
print(number)
The output result is:
6 5 4 3 2
Note:If a negative number is used as the step size, the start value must be greater than the end value.
If you only need to generate a sequence of integers and do not need to use a for loop to iterate over it, you can convert the return value of the range() function to a list or tuple, for example:
The following generates a list of integers:
Example
>>> numbers
[1, 2, 3, 4, 5]
The following generates a tuple of integers:
Example
>>> numbers
(1, 2, 3, 4, 5)
Python3 built-in functions