Math and Python: subscripts are indices

Published

2023-07-31

Subscripts are indices

Here we make explicit the connection between subscript notation in mathematics and indices in Python.

In mathematics: Say we have a collection of objects X. We can refer to individual elements of the collection by associating each element of the collection with some index from the natural numbers. Thus,

\begin{align*} x_0 &\in X \\ x_1 &\in X \\ &\ldots \\ x_n &\in X \\ \end{align*}

Different texts may use different starting indices. For example, a linear algebra text probably starts indices at one. A text on set theory is likely to use indices starting at zero.

In Python, sequences—lists, tuples, and strings—are indexed in this fashion. All Python indices start at zero, and we refer to Python as being zero indexed.

Indexing works the same for lists, tuples, and even strings. Remember that these are sequences—ordered collections—so each element has an index, and we may access elements within the sequence by its index.

my_list = ['P', 'O', 'R', 'C', 'U', 'P', 'I', 'N', 'E']

We start indices at zero, and for a list of length n, the indices range from zero to n - 1.

It’s exactly the same for tuples.

my_tuple = ('P', 'O', 'R', 'C', 'U', 'P', 'I', 'N', 'E')

The picture looks the same, doesn’t it? That’s because it is! It’s even the same for strings.

my_string = 'PORCUPINE'

While we don’t explicitly separate the characters of a string with commas, they are a sequence nonetheless, and we can read characters by index.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).