Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

range: integer sequences without building a list

range represents an immutable sequence of integers. It stores bounds and a step rather than keeping every individual value in memory.

Version: Python 3.14

Syntax

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

In range(stop), the start is 0 and the step is 1. range(start, stop, step) lets you specify all three values. The stop boundary is excluded: range(2, 9, 3) represents 2, 5 and 8.

A positive step moves upwards and a negative step downwards. Bounds that do not match the direction produce an empty range, not an error. A zero step raises ValueError. Arguments must be integers or objects supporting __index__; a step of 0.5 is not allowed.

A range supports iteration, indexing, slicing and membership checks. It is not a generator: you can iterate over it again without recreating it. You cannot add an element with append. If you really need a list, call list explicitly and account for the memory cost.

The example uses list only to display short results. In a normal loop, use the range without this conversion. In CPython, an enormous range may exist even when its length exceeds the limit accepted by len; constructing it does not allocate a list of every number.

Examples

print(list(range(2, 9, 3)))
print(list(range(5, 0, -2)))
print(list(range(5, 0)))
print(4 in range(0, 10, 2))
try:
    range(0, 5, 0)
except ValueError:
    print("ValueError")

Result

[2, 5, 8]
[5, 3, 1]
[]
True
ValueError

Sources