icon

KE Programmer

Python slicing, also why indices start at zero
Published on Oct 12, 2026 15:02 by KE Programmer

Table of Contents

1. Intro

In Python (and several other popular languages), sequence indices typically start at 0.

And when expressing ranges and slices the half-open interval convention is used, the start index is typically included while the stop index is excluded e.g.

somelist[0:5] - a slice of the first 5 items, indices 0 - 4 inclusive

range(3, 5) - generates numbers 3 and 4

How did some language designers arrive at this a useful convention?

Edsger W. Dijkstra explains in EWD831. I'll summarize below.

1.1. Expressing Sequences

There are several ways of expressing a range of natural numbers 2, 3, …, 12 (2 to 12 inclusive)

a) 2 ≤ i < 13 - lower bound included, upper bound excluded

b) 1 < i ≤ 12 - lower bound excluded, upper bound included

c) 2 ≤ i ≤ 12 - both included

d) 1 < i < 13 - both excluded

1.1.1. Desirable properties

  1. You want to get the length of the sequence i.e. 11 as the difference between the two bounds. For this, a) and b) are preferred.
  2. Indexing the sequence from the smallest natural number will force the lower bound to be unnatural where the lower bound is excluded. This is ugly (per Dijkstra). This will have you prefer a) and c)
  3. If the sequence is empty, when the upper bound is included it is forced into the realm of unnatural numbers. This will have you prefer a) and d).

Therefore, option a) is the one that satisfies all the 3.

1.1.2. Why should indices start at 0?

Going with option a) a sequence of the first N items would be:

  • 1 ≤ i < N+1 if it started at 1
  • 0 ≤ i < N if it started at 0

The second is nicer as N gives us the number of items in the sequence and the index of each item is the number of items before it.

Mathematicians have had a long running debate on whether the smallest natural number is 0 or 1. Dijkstra uses this reason to state:

And the moral of the story is that we had better regard - after all those centuries! - zero as a most natural number.