all Python 3Loopsterm
range()
range
An immutable sequence of integers: it does not hold all the numbers in memory but computes them on the fly. Used in for loops and in slices.
Syntax
range(stop) | range(start, stop) | range(start, stop, step)
range is not a generator but a full immutable sequence: you can index it, slice it, call len() on it and iterate over it as many times as you like (a generator would be exhausted after the first pass). And x in range(...) with an integer runs in O(1) — Python does the arithmetic instead of scanning every number.
Examples
print(list(range(5))) # → [0, 1, 2, 3, 4]
print(list(range(2, 8))) # → [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2))) # → [0, 2, 4, 6, 8]
print(list(range(10, 0, -2))) # → [10, 8, 6, 4, 2]
print(list(range(5, 5))) # → [] (пустой при start==stop)
print(list(range(-3, 3))) # → [-3, -2, -1, 0, 1, 2]
print(sum(range(101))) # → 5050 (сумма 1..100)
for i in range(3, 0, -1):
print(i, end=" ") # → 3 2 1
See also
Open in the full glossarydocs.python.orgReport an inaccuracy