Skip to content

Computer Science · Ch 9 — Lists

Accessing Elements in a List

9.1.1

Accessing Elements in a List

Individual elements of a list are picked out exactly the way characters are picked out of a string: write the list's name followed by the element's index in square brackets. Indexing starts at 0, so a list of n elements has valid forward indices 0 through n−1.

Forward (positive) indexing

>>> nums = [5, 10, 15, 20, 25, 30]
>>> nums[0]      # the first element
5
>>> nums[3]      # the fourth element
20

An out-of-range index is an error

Asking for an index beyond the last element does not return a default value — Python raises an IndexError:

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

The index can be any expression

The value inside the square brackets does not have to be a literal number. Any expression that evaluates to an integer works as an index:

>>> nums[2 + 3]   # same as nums[5]
30

Backward (negative) indexing

Lists support two-way indexing, again just like strings. A negative index counts from the right-hand end: index -1 is the last element, -2 the second-last, and so on.

>>> nums[-1]      # the first element from the right (the last element)
30

Using len() with indices

The built-in function len() returns the number of elements in a list. Combining len() with indexing gives two useful idioms:

>>> n = len(nums)
>>> print(n)
6
  • nums[n - 1] is always the last element, because the highest valid forward index is one less than the length:
>>> nums[n - 1]
30
  • nums[-n] is always the first element, because counting n places backward from the end lands on index 0:
>>> nums[-n]
5

These two expressions work for a list of any length, which makes them handy when you do not know in advance how many elements the list holds. …