Quick tip- Clearly communicate ranges in your functions' documentation using mathematical notations

2023/11/18

The mathematicians have a very clear way of telling ranges.

wikipedia.org/wiki/Interval_(mathematics)

The notation is simple -

  • Square brackets are inclusive
    • (a,b) means all x where a<x<b. {x∈R:a<x<b}
  • Round brackets are non-inclusive
    • [a,b] means all x where a<=x<=b. {x∈R:a≤x≤b}

You can also mix and match ranges.

Examples

  • Numbers between 0 and 3, including both 0 and 3
    • [0,3]
    • Means - {x∈R:0<=x<=3}
    • Output = {0,1,2,3}
  • Numbers between 0 and 3, including 0 and excluding 3
    • [0,3)
    • Means - {x∈R:0<=x<3}
    • Output = {0,1,2}
  • Numbers between 0 and 3, excluding 0 and including 3
    • (0,3]
    • Means - {x∈R:0<x<=3}
    • Output = {1,2,3}
  • Numbers between 0 and 3, excluding both 0 and 3
    • (0,3)
    • Means - {x∈R:0<x<3}
    • Output = {1,2}

Python Examples

The python range function - range(start, stop, step)

  • Notation:
    • [start, stop)
    • Range is : start <= val < stop

List slicing - list[start:stop:step]

  • Notation:
    • [start,stop)
    • Range is : start <= val < stop

Turns out, most standard libraries of most languages follow the [start,stop) convention.