Why sequences in computer science stop before the last number

· Faizan Khan · Read on Substack

In computer science, sequences are represented with the last term excluded. So if you want to represent the sequence 2,3,4,5. You would use [2,6), or a half-open interval.

Programming languages follow the same convention. The above sequence in python would be range(2,6).

Lets explore why we landed on this convention.

There are four ways to represent the numbers 2,3,4,5.

All of these are relevant. But only one helps in carrying out other tasks easier, and there by makes it more elegant.

So say, we wanted to add 2,3,4,5 and 6,7,8 to combine the two sequences. If we start with the first representation,

[2,6) + [6,9) = [2,9) , its symmetrical, and you can easily the end result, without having to write it out.

The second case would look something like the folowing, [2,5] + [6,8] = [2,8], it actually doesn't look bad

third case (1,6) + (5,9) = (1,9), this one is actually hard to reason about, because visually 6 in the first sequence, is higher than 5 in the second, in a sequence that representing increasing sequences.

Finally (1,5] + (5,8] = (1,8], its hard to make sense, of this because 5 appears in both subsequences, even when they are supposed to represent increasing sequences.

So we are left with first, and second representations.

Now lets say we wanted to determine the length of a sequence. [2,6) tells you that there are exactly 6-2 = 4 elements in the sequence. For the case of [2,5], you would have to add a 1. So length would be 5-2+1 = 4, to get the exact 4 length of the sequence.

Similarly, empty sequences are also easy to define with the first representation. [2,2) contains zero element. In the second convention described above, you would have to define it as [], which introduces another notation type.

In summary, a half-open interval representation, allows us to execute alof of operations, without having to learn new tricks or introduce more symbols.