Lists and positions

Lesson 32 of 54 · Python Foundations

A list keeps values in a particular order. Use one when position matters or when repeated values should remain visible. Square brackets contain the items; commas separate them. An empty list is [].

stops = ["Harbor", "Museum", "Harbor"]
print(stops)
print(len(stops))
print(stops[0], stops[-1])
['Harbor', 'Museum', 'Harbor']
3
Harbor Harbor

len counts items, including duplicates. An index is a position: the first is 0, the next is 1, and so on. Negative indices count from the end; -1 selects the last item.

item       Harbor   Museum   Harbor
index         0        1        2
from end     -3       -2       -1

For a nonempty list of length n, the last nonnegative index is n - 1. Indexing outside the available positions raises IndexError; in particular, [][0] has no first item. A guard makes the empty case explicit:

stops = []
if stops:
    first = stops[0]
else:
    first = None
print(first)
None

Here an empty list is false in a condition, and None represents the absence of a result. A list may contain different types, although a consistent item shape often makes it easier to process. Long literals may span lines inside the brackets, with an optional trailing comma.