Ranges

suggest change

range is a built-in type that represents an arithmetic sequence of integers: 0, 1, 2, ... or 10, 7, 4, 1. It's most often used to run a for loop a given number of times or to generate indexes, but it is also a full, immutable sequence type that supports len(), indexing, slicing and fast membership tests.

This article covers:

All examples were run with Python 3.13.

Creating a range

range() takes one, two or three integer arguments:

Call Produces
range(stop) 0, 1, ..., stop - 1
range(start, stop) start, start + 1, ..., stop - 1
range(start, stop, step) start, start + step, ... while before stop

The stop value is never included. A range object doesn't print its values, so wrap it in list() to see them:

print(list(range(5)))
print(list(range(2, 8)))
print(list(range(0, 20, 5)))
print(list(range(10, 0, -3)))
print(list(range(5, 0, -1)))
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[0, 5, 10, 15]
[10, 7, 4, 1]
[5, 4, 3, 2, 1]

The exclusive stop matches how slicing works: range(len(items)) produces exactly the valid indexes of items, and range(a, b) has b - a elements.

With a negative step the range counts down, and it stops when the value would be less than or equal to stop. To count down from 5 to 1 you write range(5, 0, -1), not range(5, 1, -1).

Empty ranges and errors

If start is already past stop in the direction of step, the range is empty. That is not an error:

print(list(range(5, 2)))
print(list(range(0)))
print(list(range(-3)))
print(list(range(0, 10, -1)))
try:
    range(0, 10, 0)
except ValueError as e:
    print("ValueError:", e)
try:
    range(0.5, 3)
except TypeError as e:
    print("TypeError:", e)
[]
[]
[]
[]
ValueError: range() arg 3 must not be zero
TypeError: 'float' object cannot be interpreted as an integer

Empty ranges are convenient: a loop like for i in range(n) simply does nothing when n is 0 or negative, so you don't need a special case.

A step of 0 raises ValueError, and floats raise TypeError even when they hold a whole number like 3.0. Use int() or round() first if you computed the bound with floating-point math. See the "Float ranges" section below for non-integer steps.

A range is a lazy, immutable sequence

range() does not build a list. It returns a small range object that stores only start, stop and step and computes each element on demand:

import sys

r = range(10, 100, 7)
print(r)
print(type(r))
print(len(r))
print(r[0], r[1], r[-1])
print(r[2:5])
print(r[::-1])
print(r.start, r.stop, r.step)
print(sys.getsizeof(r))
print(sys.getsizeof(list(r)))
big = range(10**18)
print(sys.getsizeof(big), big[-1])
range(10, 100, 7)
<class 'range'>
13
10 17 94
range(24, 45, 7)
range(94, 3, -7)
10 100 7
48
168
48 999999999999999999

Things to notice:

In Python 2, range() returned a list and the lazy version was called xrange(). Python 3's range is the old xrange, improved; xrange no longer exists.

Ranges are immutable, so you can't assign to r[0], and range can't be subclassed. When you need a mutable list of numbers, convert it with list(range(...)).

Ranges are reusable

A range is an iterable, not an iterator. Every for loop or iter() call starts a fresh pass from the beginning, so you can loop over the same range many times. That's different from a generator, which is exhausted after one pass:

r = range(3)
it1 = iter(r)
it2 = iter(r)
print(next(it1), next(it1), next(it2))
for x in r:
    print(x, end=" ")
for x in r:
    print(x, end=" ")
print()
0 1 0
0 1 2 0 1 2

See Iterator vs Iterable vs Generator for more on the distinction.

Very large ranges and len()

Range arguments can be arbitrarily large integers, but len() must fit in a C ssize_t (sys.maxsize, 263 - 1 on 64-bit systems). Indexing still works past that limit:

import sys

huge = range(sys.maxsize * 2)
print(huge[-1])
try:
    print(len(huge))
except OverflowError as e:
    print("OverflowError:", e)
18446744073709551613
OverflowError: Python int too large to convert to C ssize_t

Membership, index and count

Because a range knows its formula, in with an integer is computed in constant time: Python checks that the value is between the bounds and that (value - start) % step == 0. Testing membership in a billion-element range is instant:

r = range(0, 1_000_000_000, 3)
print(999_999_999 in r)
print(999_999_998 in r)
print(r.index(300))
print(r.count(9))
print(5.0 in range(10))
print(5.5 in range(10))
try:
    r.index(4)
except ValueError as e:
    print("ValueError:", e)
True
False
100
1
True
False
ValueError: 4 is not in range

index() and count() are also O(1) for integers. count() can only return 0 or 1, because a range never repeats a value.

The fast path only applies to int (and bool) values. Testing a float like 5.0 gives the right answer, but Python falls back to comparing it with every element:

import timeit

r = range(10_000_000)
print(f"int:   {timeit.timeit('9_999_999 in r', globals=globals(), number=1):.6f}s")
print(f"float: {timeit.timeit('9_999_999.0 in r', globals=globals(), number=1):.6f}s")
int:   0.000003s
float: 0.267974s

Exact timings depend on the machine, but the float lookup is roughly 100,000 times slower here.

Range membership is handy for bounds checks that read naturally:

def check_port(port):
    if port not in range(1, 65536):
        raise ValueError(f"invalid port: {port}")
    return port

print(check_port(8080))
try:
    check_port(70000)
except ValueError as e:
    print(e)
8080
invalid port: 70000

1 <= port <= 65535 is equivalent for integers and slightly faster; the range version is mostly a matter of taste. Note that it rejects floats only if they aren't whole numbers: 8080.0 in range(1, 65536) is True.

Comparing and hashing ranges

Two ranges are equal if they produce the same sequence of values, even if their arguments differ. A range is never equal to a list:

print(range(0) == range(5, 5))
print(range(0, 3) == range(0, 4, 1)[:3])
print(range(1, 10, 2) == range(1, 11, 2))
print(range(3) == [0, 1, 2])
print(list(range(3)) == [0, 1, 2])
print(hash(range(1, 10, 2)) == hash(range(1, 11, 2)))
True
True
True
False
True
True

Ranges are hashable, so they can be dictionary keys or set members. Equal ranges have equal hashes. Ordering comparisons (<, >) are not supported.

Other ways to use a range

A range works anywhere an iterable is accepted:

first, second, third = range(3)
print(first, second, third)
print(tuple(range(4)), set(range(3)))
print(bool(range(0)), bool(range(1)))
print(*range(5))
print(list(zip(range(1, 4), "abc")))
print(dict.fromkeys(range(3), 0))
print(max(range(10, 0, -3)), min(range(10, 0, -3)))
0 1 2
(0, 1, 2, 3) {0, 1, 2}
False True
0 1 2 3 4
[(1, 'a'), (2, 'b'), (3, 'c')]
{0: 0, 1: 0, 2: 0}
10 1

An empty range is falsy, so if r: tests whether it has any elements.

Ranges are also a natural source for comprehensions and aggregate functions:

grid = [[r * 3 + c for c in range(3)] for r in range(3)]
print(grid)
pairs = [(i, j) for i in range(4) for j in range(i + 1, 4)]
print(pairs)
squares = {n: n * n for n in range(1, 6)}
print(squares)
print(sum(range(1, 101)))
print(sum(range(1, 101, 2)))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
5050
2500

Looping patterns

Repeat something N times

When you don't need the counter, name it _ by convention:

for _ in range(3):
    print("hello")
hello
hello
hello

Indexes: prefer enumerate

range(len(items)) works, but when you need both the index and the item, enumerate() is clearer and avoids indexing back into the list:

colors = ["red", "green", "blue"]
for i in range(len(colors)):
    print(i, colors[i])
for i, color in enumerate(colors):
    print(i, color)
for i, color in enumerate(colors, start=1):
    print(i, color)
0 red
1 green
2 blue
0 red
1 green
2 blue
1 red
2 green
3 blue

Use range with indexes when you actually need index arithmetic, for example comparing each element with its predecessor:

nums = [3, 8, 1, 9, 4]
for i in range(1, len(nums)):
    print(nums[i] - nums[i - 1], end=" ")
print()
5 -7 8 -5

(For this particular case itertools.pairwise(nums) is another option.)

Counting backwards

You can count down with a negative step, but reversed() is easier to get right because you don't have to work out the off-by-one bounds:

nums = [3, 8, 1, 9, 4]
for i in range(len(nums) - 1, -1, -1):
    print(nums[i], end=" ")
print()
for i in reversed(range(len(nums))):
    print(nums[i], end=" ")
print()
print(list(reversed(range(1, 10, 3))))
4 9 1 8 3
4 9 1 8 3
[7, 4, 1]

reversed() on a range is O(1); it doesn't build a list. range(...)[::-1] also works and returns a new range.

Processing in chunks

A step lets you walk a sequence in fixed-size blocks; slicing handles the shorter last chunk automatically:

data = list("abcdefghij")
for i in range(0, len(data), 4):
    print(data[i:i + 4])
['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']
['i', 'j']

Python 3.12+ also has itertools.batched(), which works on any iterable, not just sequences:

from itertools import batched

print(list(batched(range(10), 4)))
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9)]

The loop variable survives the loop

After a for loop the variable keeps its last value. If the range was empty, the variable is never assigned:

for i in range(3):
    pass
print("after loop, i =", i)
for j in range(0):
    pass
try:
    print(j)
except NameError as e:
    print("NameError:", e)
after loop, i = 2
NameError: name 'j' is not defined

Note that i ends at 2, not 3: the loop never assigns the stop value. See Variable leaking in list comprehensions and for loops.

Ranges and slices

A slice and a range describe the same kind of arithmetic progression. slice.indices(length) resolves None and negative values for a sequence of a given length, and the result can be passed straight to range():

data = "abcdefghij"
s = slice(1, None, 3)
print(data[s])
print(s.indices(len(data)))
idx = range(*s.indices(len(data)))
print(idx, list(idx))
print([data[i] for i in idx])
print(range(len(data))[s])
beh
(1, 10, 3)
range(1, 10, 3) [1, 4, 7]
['b', 'e', 'h']
range(1, 10, 3)

This is useful when implementing __getitem__ on your own classes (see Slice objects). Slicing range(len(data)) gives the same answer in one step.

Inclusive ranges

There is no built-in inclusive range. Adjust stop by one in the direction of the step:

def inclusive_range(start, stop, step=1):
    return range(start, stop + (1 if step > 0 else -1), step)

print(list(inclusive_range(1, 10, 3)))
print(list(inclusive_range(1, 10)))
print(list(inclusive_range(5, 1, -1)))
[1, 4, 7, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[5, 4, 3, 2, 1]

stop is only included if the step lands on it: inclusive_range(1, 10, 4) gives 1, 5, 9.

Float ranges

range only accepts integers. The tempting fix, adding a float step in a while loop, accumulates rounding error:

x = 0.0
values = []
while x < 1.0:
    values.append(x)
    x += 0.1
print(len(values), values[-1])
11 0.9999999999999999

We wanted 10 values (0.0 to 0.9) but got 11, because after ten additions x is slightly less than 1.0.

The robust approach is to loop over integers and compute each float from the index. Dividing by an integer gives the cleanest values:

print([i / 10 for i in range(11)])

def frange(start, stop, step):
    n = round((stop - start) / step)
    return [start + i * step for i in range(n)]

print(frange(0.0, 1.0, 0.1))
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

frange always produces the right number of values; the tiny representation errors like 0.30000000000000004 are inherent to binary floating point (use decimal.Decimal or fractions.Fraction if you need exact values, see Decimal and fractions). If you use NumPy, numpy.linspace(start, stop, num) and numpy.arange() do this for you.

Unbounded counting

A range always has an end. To count forever, use itertools.count() and stop with break or itertools.islice():

from itertools import count, islice

for n in count(10, 5):
    if n > 30:
        break
    print(n, end=" ")
print()
print(list(islice(count(1), 5)))
10 15 20 25 30
[1, 2, 3, 4, 5]

See itertools.count. For a random number from a range, use random.randrange(start, stop, step) or random.choice(range(...)), see Random module.

Summary

Task Use
Loop N times for _ in range(n)
Numbers from a to b, excluding b range(a, b)
Every k-th number range(start, stop, k)
Count down from n to 1 range(n, 0, -1) or reversed(range(1, n + 1))
Index and item enumerate(items)
Indexes in reverse reversed(range(len(items)))
Fixed-size chunks range(0, len(seq), size) or itertools.batched()
Include the end value range(a, b + 1)
Is x a valid value x in range(a, b) (O(1) for ints)
Float steps [i / 10 for i in range(n)] or numpy.linspace
Count forever itertools.count()
Get a list list(range(...))

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents