Python range() function usage
In Python 2.x, the range() function creates a list of integers, typically used in for loops.
Note:Python 3 range() returns an iterable object (of type object) rather than a list, so printing it does not print a list. For details, see Python 3 range() usage notes.
Function syntax
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 does not include stop. For example: range(0, 5) is [0, 1, 2, 3, 4] with no 5
- step: the step size, defaulting to 1. For example: range(0, 5) is equivalent to range(0, 5, 1)
Example
range
(
10
)
From 0 to 9
[
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
]
range
(
1
,
11
)
From 1 to 10
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
range
(
0
,
30
,
5
)
Step size of 5
[
0
,
5
,
10
,
15
,
20
,
25
]
range
(
0
,
10
,
3
)
Step size of 3
[
0
,
3
,
6
,
9
]
range
(
0
, -
10
, -
1
)
Negative numbers
[
0
, -
1
, -
2
, -
3
, -
4
, -
5
, -
6
, -
7
, -
8
, -
9
]
range
(
0
)
[
]
range
(
1
,
0
)
[
]
The following is the use of range in a for loop, iterating over each letter of runoob:
x
=
'
runoob
'
for
i
in
range
(
len
(
x
)
)
: ...
(
x
[
i
]
)
...
r
u
n
o
o
b
Python built-in function