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
| Parameter | Description |
|---|---|
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
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]
for i in range(3):
print("round", i + 1)
Output
round 1 round 2 round 3
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
In other languages
range()· PHP
Related
enumerate()· Loop over an iterable and get each item together with its index, as (index, item) pairs. The start number is configurable.len()· Return the number of items in a container: characters in a string, items in a list, keys in a dict, and so on.list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.reversed()· Return an iterator that goes through a sequence backwards, without copying it. Works on lists, tuples, strings and ranges.- Python For Loops · tutorial