PythonConditional Statements and LoopsPython range and iteration

How does the `range()` function work?

Question 52 of 88 · Updated

On this page

Python's range() creates an immutable sequence representing an arithmetic progression of integers. It is commonly used with for loops to repeat a task a specified number of times, traverse integer indexes, or generate evenly spaced integer values.

Although often called the range function, range is a built-in sequence type in Python 3. It stores the information needed to represent the progression rather than materializing a separate element for every position.

1. Syntax: the three ways to construct a range#

FormStartStopStep
range(stop)0stop (exclusive)1
range(start, stop)startstop (exclusive)1
range(start, stop, step)startstop (exclusive)step
PYTHON
print(list(range(4)), list(range(2,6)), list(range(2,10,3)))

Output:

[0, 1, 2, 3] [2, 3, 4, 5] [2, 5, 8]

The first progression starts at zero and stops before four. The second starts at two and stops before six. The third advances by three and stops before reaching or crossing ten.

The stop value is excluded even if the progression would otherwise land exactly on it. This half-open convention is consistent with ordinary Python slicing and makes range(n) convenient for n repetitions.

The list conversion in these examples is only for displaying small progressions. A for loop can traverse the range directly.

2. How values are generated#

For a nonnegative index i, the mathematical value at that position is:

value = start + i * step

A positive step permits values strictly smaller than stop. A negative step permits values strictly greater than stop.

Consider range(2, 10, 3). Its candidate values are 2, 5, 8 and 11. The value 11 fails the upper-bound test, so the progression contains only 2, 5 and 8.

Loading diagram…

This is a conceptual model of traversing a positive-step range. The actual range implementation is not required to use this precise loop internally. It can compute individual elements directly from the progression parameters.

3. Negative steps and empty ranges#

PYTHON
print(list(range(5,0,-2)), list(range(0,5,-1)), list(range(3,3)))

Output:

[5, 3, 1] [] []

The first range begins at five and decreases by two until the next candidate would no longer be greater than zero. Zero itself is not included.

The second range is empty because the starting value is already below the stopping boundary for a negative step. The third range is empty because start and stop are equal.

Step directionCondition for a nonempty range
Positivestart < stop
Negativestart > stop

The step cannot be zero. A zero step would not define a valid range progression and raises ValueError at construction.

Do not assume that an incorrectly directed step will raise an exception. It can produce a perfectly valid but empty range.

4. Calculating the number of elements#

The length of an arithmetic progression can be calculated without generating every element. For a positive step s, the mathematical number of elements is:

max(0, (stop - start + s - 1) // s)

For a negative step, let d = -step, which is positive. The mathematical length is:

max(0, (start - stop + d - 1) // d)

These formulas perform integer ceiling division for the nonempty cases and return zero for empty cases. They assume integer parameters and a nonzero step.

For example, range(2, 10, 3) has length (10 - 2 + 3 - 1) // 3 = 10 // 3 = 3.

In ordinary application code, use len(r) when the length is representable by Python's length interface. There is usually no reason to implement the formula yourself. The formula is helpful for understanding the progression and for reasoning about unusually large integer bounds.

The mathematical number of elements can exceed the largest length representable by CPython's len function. Such a range can still be constructed; len may raise OverflowError. Section 8 demonstrates this distinction.

5. A range is a sequence, not a list#

PYTHON
r=range(2,12,3) print(r.start,r.stop,r.step,len(r)) print(r[0],r[-1],list(r[1:3]))

Output:

2 12 3 4
2 11 [5, 8]

The range represents 2, 5, 8 and 11. Its read-only start, stop and step attributes expose the construction parameters.

Like other sequences, it supports integer indexing, negative indexes and slicing. A slice of a range returns another range object, so selecting a sub-progression does not require constructing a list of all the selected values.

The range object is immutable. It has no append method, and assigning to one of its positions raises TypeError.

If you need a mutable collection, explicitly convert a suitably bounded range using list(r). Do not materialize a very large range just to inspect a few elements.

6. Reversing a progression#

PYTHON
r=range(10) print(list(r[::-1]),list(reversed(range(3))))

Output:

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] [2, 1, 0]

The slice r[::-1] creates a reversed range. The reversed function returns a reverse iterator for a supported sequence such as range(3).

Both examples materialize only small results for display. When processing a large progression in reverse, iterate over the reversed range or its reverse iterator directly.

A descending progression can also be expressed explicitly with a negative step. Choose the form that makes the intended bounds easiest to understand.

7. Equality depends on represented values#

PYTHON
print(range(0,3,2)==range(0,4,2),range(0)==range(9,2)) print(range(3)==[0,1,2])

Output:

True True
False

The first two ranges both represent the sequence 0, 2, despite having different stop attributes. The empty ranges likewise represent the same empty sequence.

Range equality between range objects compares the represented sequences, not necessarily their original start, stop and step parameters. Equal ranges can have different construction attributes.

A range and a list with the same apparent values do not necessarily compare equal. The final expression compares a range with a list and returns False. If cross-type elementwise equality is specifically needed, implement an appropriate comparison without blindly materializing enormous sequences.

8. Very large ranges and memory usage#

PYTHON
r=range(10**30) print(r[10**20],(10**30-1) in r,10**30 in r)

Output:

100000000000000000000 True False

This example constructs a progression with 1030 mathematical elements without storing 1030 individual integers.

Range storage does not grow linearly with the number of represented elements. It stores a fixed number of integer parameters and related metadata. Since Python integers have arbitrary precision, the byte cost of those integers can grow with the magnitudes of the bounds. It is therefore more precise to describe range as constant in the number of stored progression parameters, not universally constant in bit-level storage.

On the tested CPython 3.13.5 runtime, len(range(10**30)) raises OverflowError because the mathematical length exceeds the platform's supported sequence length result.

This does not make traversing all those values practical. Iteration still requires work for each value consumed, and list(r) would attempt to materialize the progression, potentially failing because of memory or length limits.

For ordinary fixed-size operands, construction, indexing and optimized integer membership require a bounded number of arithmetic operations, independent of the number of represented elements. Actual big-integer arithmetic costs depend on operand bit lengths.

9. Which argument types are accepted?#

The range constructor accepts integers and objects implementing the integer-index protocol, __index__.

PYTHON
class Count: def __index__(self): return 3 print(list(range(Count())))

Output:

[0, 1, 2]

The Count object provides the exact integer 3 through __index__, so it can be used as a range argument.

A floating-point number such as 3.0 is not accepted merely because its mathematical value is integral. range(3.0) raises TypeError. An object providing only __int__ is not necessarily a valid range argument.

Avoid blindly applying int() to a floating-point input: int truncates toward zero, which may silently discard an unwanted fractional part. Validate the input according to the task before constructing the range.

For decimal or floating-point progressions, use an explicitly defined numerical approach with appropriate precision and endpoint semantics rather than assuming range supports noninteger steps.

10. A range can be traversed repeatedly#

PYTHON
r=range(3) a=iter(r) print(next(a),list(a),list(r))

Output:

0 [1, 2] [0, 1, 2]

The iterator a has its own traversal position. After reading its first element, only 1 and 2 remain. Consuming a does not exhaust the range itself, because range is a reusable iterable.

This distinction matters when a function expects to traverse a source more than once. A range can provide a fresh iterator for each traversal. A one-shot generator or iterator generally cannot restart after exhaustion.

The earlier loop and membership lessons introduced iterator consumption. Here the important point is that compact representation and reusable iteration are distinct properties: a range is not a generator.

11. Practical example: divide a sequence into batches#

PYTHON
items=list("abcdefg") print([items[i:i+3] for i in range(0,len(items),3)])

Output:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

The range supplies the starting indexes 0, 3 and 6. Each slice takes up to three items from the list. The final slice contains only one item because Python slicing stops at the available sequence boundary.

Loading diagram…

This pattern is useful when a finite indexable collection must be processed in chunks. A general-purpose helper should validate that its batch size is a positive integer. A zero step raises ValueError, and a negative batch size would not express the intended forward batching rule.

For n items and a positive batch size b, this example produces ceil(n/b) nonempty batches when n is positive. The list slices collectively copy n element references, giving O(n) time and O(n) output storage under the usual list model.

For very large or streaming inputs, prefer an iterator-based batching strategy or process each slice without storing every batch. Do not assume that using range makes the complete algorithm memory-independent.

12. Membership, index and count#

PYTHON
r=range(9,0,-2) print(3 in r,4 in r,r.index(3),r.count(3))

Output:

True False 3 1

The represented values are 9, 7, 5, 3 and 1. The integer 3 appears at index 3, whereas 4 does not occur. Since a nonzero-step arithmetic progression cannot contain repeated values, count returns one for this matching integer.

For ordinary integer membership, Python can test bounds and arithmetic alignment without scanning all values. For example, a candidate must be within the correct stopping boundary and its difference from start must be divisible by step.

Other candidate types may use equality-based traversal instead of optimized integer arithmetic. Do not assume membership or index operations for all arbitrary objects have the same complexity as ordinary integer lookups.

Use index when the actual position is needed. If the value does not occur, index raises ValueError rather than returning a special missing index.

13. Errors and boundary cases#

The following six operations were tested independently.

Expression or operationExpected exception
range(1,5,0)ValueError
range(3.0)TypeError
range(3)[3]IndexError
range(3).index(9)ValueError
len(range(10**30)) on the tested CPython runtimeOverflowError
Assigning to range(3)[0]TypeError

Other common mistakes include including the exclusive stop by accident, choosing a step with the wrong sign, assuming range is a list or generator, and converting a huge range to a list unnecessarily.

For an inclusive ascending interval from integer a through integer b, range(a, b + 1) is appropriate when the desired step is one. For a descending interval with step minus one, range(a, b - 1, -1) includes b when the bounds are valid. For other steps, explicitly consider whether the final endpoint is aligned with the progression.

14. When should you use range?#

Use range for integer arithmetic progressions, known-count repetitions, offsets and other operations that genuinely need integer positions.

For traversing existing collection values, direct iteration is often clearer than indexing with range(len(items)). When both the position and value are needed, enumerate(items) usually expresses that intention directly.

Use a list or another materialized collection if the task requires element replacement, arbitrary modifications or stored values unrelated to an arithmetic progression.

The appropriate data structure depends on how the values are generated, how they are accessed and whether they need to be changed.

Frequently asked questions#

Does range include its stop value?#

No. Stop is exclusive for both positive and negative steps.

Is range a generator?#

No. In Python 3, range is an immutable reusable sequence type. Iterating over it creates an iterator.

Can range use negative numbers?#

Yes. Start and stop can be negative, and the step can be negative as long as it is nonzero.

Why does range save memory?#

It represents a progression using a small fixed number of integer parameters rather than storing a separate element for each position. Materializing it into a list removes that advantage.

Can range return floating-point numbers?#

No. The constructor requires integer-compatible arguments supporting the appropriate index protocol.

Does a large range make a for loop faster?#

It avoids materializing an entire list, but each consumed value still requires iteration and any associated loop-body work. Measure representative workloads rather than assuming a universal speedup.

Interview-ready answer#

Python's range is an immutable sequence type representing an arithmetic progression of integers. It accepts range(stop), range(start, stop) or range(start, stop, step), with default start zero and default step one. Stop is exclusive, and step must be nonzero. A negative step supports descending sequences, while incompatible bounds can produce an empty range. Unlike a list, range stores progression parameters instead of every element, supports indexing and slicing, and can be iterated repeatedly. Integer membership can exploit arithmetic properties. Very large ranges may exceed the length supported by len even though construction succeeds.

Official references#

Verification note: Ten runnable Python examples matched their documented outputs on CPython 3.13.5. Six expected-exception tests passed. The mathematical length formulas were additionally compared with len(range(start, stop, step)) for all 968 combinations of starts and stops from -5 through 5 and nonzero steps from -4 through 4. Both fenced Mermaid diagrams were manually reviewed; the Mermaid package and CLI were not available locally, so parser-level and public-site rendering were not verified. Official reference links are supplied under the authorized offline research exception. Live documentation and Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design