Python3 range() Function Usage
The Python3 range() function returns an iterable object (of type object), not a list, so printing it does not print a list.
The Python3 list() function is an object iterator that can convert the iterable returned by range() into a list; the resulting variable is of list type.
Python2 The range() functionreturns a list.
Function syntax
range(stop)
range(start, stop[, step])
Parameter Description:
- start: counting begins at start. The default is 0. For example, range(5) is equivalent to range(0, 5)
- stop: counting ends at stop, but stop itself is not included. For example: range(0, 5) is [0, 1, 2, 3, 4] with no 5
- step: the stride, defaulting to 1. For example: range(0, 5) is equivalent to range(0, 5, 1)
Example
If only the start and end values are given, the step defaults to 1:
Example
for
number
in
range
(
1
,
6
)
:
(
number
)
The output is:
1
2
3
4
5
If only one argument is given, it generates a sequence of integers starting from 0; that argument is the end value and the step defaults to 1:
Example
for
number
in
range
(
6
)
:
(
number
)
The output is:
0
1
2
3
4
5
You can specify a step so that the value increases by a different amount each time:
Example
for
number
in
range
(
1
,
6
,
2
)
:
(
number
)
The output is:
1
3
5
Note: The end value 6 is not included.
In addition, we can use a negative step to generate the sequence in reverse order from the end value:
Example
for
number
in
range
(
6
,
1
,
1
)
:
(
number
)
The output is:
6
5
4
3
2
**Note:** If a negative step is used, 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 iterate over it with a for loop, you can convert the value returned by range() into a list or tuple, for example:
The following generates a list of integers:
Example
numbers
=
list
(
range
(
1
,
6
)
)
numbers
[
1
,
2
,
3
,
4
,
5
]
The following generates a tuple of integers:
Example
numbers
=
tuple
(
range
(
1
,
6
)
)
numbers
(
1
,
2
,
3
,
4
,
5
)
Python3 built-in function