Skip to content

Informatics Practices · Ch 4 — Working with Lists and Dictionaries

Accessing Elements in a List

4.1.1

Accessing Elements in a List

Once data sits inside a list, you need a way to reach any single element directly — without walking through the others. Python does this with an index: every element in a list is automatically given a position number, and you use that number, inside square brackets, to pull the element out.

Forward (positive) indexing

Index values are assigned in increasing order starting from 0: the first element has index 0, the second has index 1, and so on. To access an element, write the list's name followed by square brackets containing the index of that element.

>>> list1 = [2,4,6,8,10,12]
>>> list1[0]        # first element of list1
2
>>> list1[3]        # fourth element of list1
8

The pattern to internalise: index = position minus one. The fourth element lives at index 3, not 4 — forgetting the zero start is the single most common indexing slip.

Index out of range

Asking for an index the list does not have is an error, not an empty result:

>>> list1[15]
IndexError: list index out of range

list1 has six elements (indexes 0 to 5), so index 15 simply does not exist, and Python raises an IndexError.

An expression as an index

The index need not be a bare number — any expression that evaluates to an integer works inside the brackets. Python computes the expression first, then uses the result as the index:

>>> list1[1+4]      # same as list1[5]
12

Backward (negative) indexing

Python also lets you count from the end of the list using negative index values: index -1 is the last element, -2 the one before it, and so on back to the front.

>>> list1[-1]       # last element, counted from the right
12

Using the length of the list

The built-in len() function returns the number of elements, and that number links the two indexing schemes together:

>>> n = len(list1)
>>> print(n)
6
>>> list1[n-1]      # last element of list1
12
>>> list1[-n]       # first element of list1
2

With n elements, the valid positive indexes run from 0 to n-1, and the valid negative indexes run from -1 back to -n. So list1[n-1] is always the last element and list1[-n] is always the first — two useful identities worth remembering. …