Python 3 reference · Built-in Functions

Python range() Function

Create an immutable sequence of integers from start up to (but not including) stop, in steps. Used in for loops.

Python 3 Since 3.0

Syntax

range(stop)
range(start, stop, step=1)

Parameters

ParameterDescription
start optional The first number. Default: 0
stop The end; this number is not included.
step optional The difference between numbers; can be negative. Default: 1

Return value

A range object (a lazy sequence; it doesn't store every number).

Examples

Start, stop and stepTry it yourself
print(list(range(5)))
print(list(range(2, 8)))
print(list(range(0, 20, 5)))
print(list(range(5, 0, -1)))

Output

[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]
Repeat something n timesTry it yourself
for i in range(3):
    print("round", i + 1)

Output

round 1
round 2
round 3
Ranges are lazy and fastTry it yourself
r = range(0, 1_000_000_000, 2)
print(len(r), r[10], 999_999_998 in r)  # no huge list is built

Output

500000000 20 True

Common mistakes

range(1, 10) stops at 9. To include the end, use range(1, 11). To loop over a list with indexes, prefer enumerate() over range(len(items)).

Version history

VersionChange
Python 3.0Added