Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

Python range(): Start, Stop, Step and Loop Examples

Published

Python

range() represents an immutable sequence of integers. It is useful for a counted loop, selected positions or a numeric progression. It does not create a list of every number, and it is not a generator: a range can be indexed, sliced and iterated over again.

These independent examples were executed with Python 3.12.14. Converting a small range to a list makes its values visible; avoid doing that solely to loop over a very large range.

Choose stop, start and step

The three forms are range(stop), range(start, stop) and range(start, stop, step). The defaults are start 0 and step 1. In every form, the stop value is excluded.

assert list(range(4)) == [0, 1, 2, 3]
assert list(range(3, 7)) == [3, 4, 5, 6]
assert list(range(2, 10, 3)) == [2, 5, 8]

labels = []
for number in range(1, 4):
    labels.append(f"job-{number}")
assert labels == ["job-1", "job-2", "job-3"]
print(labels)

Use a negative step to count down

A positive step needs a start below the stop to produce values. A negative step needs a start above the stop. A mismatched direction produces an empty range rather than an error. To include zero in a descending sequence, place the exclusive stop below zero.

assert list(range(5, 0, -2)) == [5, 3, 1]
assert list(range(3, -1, -1)) == [3, 2, 1, 0]
assert list(range(5, 0)) == []
assert list(range(0, 5, -1)) == []
assert list(range(3, 3)) == []
assert list(range(-3)) == []
print(list(range(3, -1, -1)))

Reject a zero step and non-integer arguments

A zero step raises ValueError. Arguments must be integers or objects that supply the integer-index protocol; ordinary floats do not qualify, even 3.0. Converting a decimal with int() truncates it, so do not use that conversion to silently accept an invalid count.

cases = [((1, 5, 0), ValueError), ((3.0,), TypeError)]
for arguments, expected_error in cases:
    try:
        range(*arguments)
    except expected_error:
        pass
    else:
        raise AssertionError("Expected invalid range arguments to fail")

print("Both invalid inputs were rejected")

Distinguish a range from its iterator

A range stores a compact description of the progression instead of one object per result. Traversing a billion values still takes substantial work; compact storage does not make the loop free. An iterator created from a range keeps a current position and is exhausted after use.

values = range(2, 10, 2)
assert len(values) == 4
assert values[0] == 2
assert values[-1] == 8
assert list(values[1:3]) == [4, 6]
assert 6 in values and 7 not in values
assert list(values) == list(values) == [2, 4, 6, 8]

iterator = iter(values)
assert next(iterator) == 2
assert list(iterator) == [4, 6, 8]
assert list(iterator) == []
assert list(values) == [2, 4, 6, 8]
print(values)

Prefer direct iteration or enumerate for collection items

range(len(items)) is useful when you specifically need positions, but unnecessary when you only need each value. enumerate() supplies both without a separate indexing expression. Do not change the list’s length while using a range computed from its old length.

services = ["web", "mail", "dns"]
numbered = list(enumerate(services, start=1))
assert numbered == [(1, "web"), (2, "mail"), (3, "dns")]

selected = []
for index in range(0, len(services), 2):
    selected.append(services[index])
assert selected == ["web", "dns"]
print(numbered)

Use small progressions for totals and tables

Supply a range directly to sum() rather than creating a temporary list. For a table, each inner range starts a fresh iteration. Check both ends of a sequence when fixing off-by-one errors.

assert sum(range(1, 6)) == 15

table = []
for row in range(1, 4):
    table.append([row * column for column in range(1, 4)])
assert table == [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
print(table)

Verification: All six blocks ran independently, covering exclusive stops, empty ranges, negative steps, invalid arguments and iterator exhaustion. References: Python range objects. Related: for and while loops and nested loops.

Related guides

Account services are unavailable until the production backend is configured.