BYU logo Computer Science

List indexing

The items in a list are indexed starting from zero:

names = ['Maria', 'Mariano', 'Anna', 'Antonino']

a list of names, showing that the first item is indexed at zero, the next at 1, and so forth

To access individual items in the list, use square brackets:

grandmother = names[2]

In this case, grandmother would have the value Anna. Likewise, names[0] would be Maria.

Going past the end of the list

The last item is at len(names) - 1:

last_name = names[len(names) - 1]

Trying to index past the end of a list will create an error:

names[7]

The error you will see:

IndexError: list index out of range

Negative indexing

We can count backwards from the end using negative numbers, so names[-1] is Antonino.

Likewise, names[-3] is Mariano.

Mutating lists

Lists are mutable, meaning you can change them:

if __name__ == '__main__':
    names = ['Maria', 'Mariano', 'Anna', 'Antonino']

    names[1] = 'Carmelo'
    print(names)

This will print:

['Maria', 'Carmelo', 'Anna', 'Antonino']