Counting with Python's Range

A range represents an arithmetic progression with an excluded stop value and a nonzero step.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read the last value
  2. Check the direction
  3. Derive positions from the starting point and stride
  4. Use small examples to check direction and range length

Read the last value

The progression range(2, 9, 3) produces 2, 5, and 8. Adding another step would give 11, which reaches or passes the stop. This is the same half-open boundary useful for indices.

Check the direction

The progression range(7, 1, -2) produces 7, 5, and 3. The bounds 7 and 1 with the default positive step give an empty progression. Write the intended first value and update in your trace to catch the wrong sign before indexing a collection.[1]

Derive positions from the starting point and stride

The sequence range(3, 14, 4) yields 3, 7, and 11 because each next value adds four and the next 15 would reach or exceed the excluded stop. For range(12, 1, -4) the values are 12, 8, and 4. The next zero lies outside the decreasing progression. Write the first, last, and hypothetical next value when investigating a boundary. Half-open slice bounds use a similar stop convention in forward indexing.

Use small examples to check direction and range length

A range ending at its starting point is empty for either nonzero direction. A positive step with a larger start than stop is also empty. Python rejects step zero because it cannot describe a progressing arithmetic sequence.

If you use a range to visit positions in a list of length \(n\), the ordinary forward indices use start zero and stop \(n\). A reverse traversal can start at \(n-1\) when \(n>0\) and use an excluded stop of minus one. Verify the zero-length and single-item cases before using the indices. Off-by-one errors are easiest to see at those lengths.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩