Sub topic 2
Reading Items by Index
This chapter covers how to read one item from a list by position. It assumes you can run Python code, know int, str and bool, and can write a for loop and call a method. Slicing, which reads several items at once, comes in the next chapter.
Positions start at zero
A list stores its items in order. The position of an item is its index, and the first item has index 0. You read an item by writing the list, then the index in square brackets.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[3]) # date
print(len(fruits)) # 4The last valid index is len(fruits) - 1, not len(fruits). A list of four items has indices 0 to 3.
Zero-based indexing follows from how CPython, the standard Python implementation, stores a list. A list holds a contiguous array of references, and each reference points to an item object. Index i means "go i slots from the start of the array". Python can therefore read any index in constant time, whether the list holds ten items or ten million.
Negative indices count from the end
A negative index counts backward from the end. -1 is the last item, -2 is the one before it, and so on.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[-1]) # date
print(fruits[-2]) # cherry
print(fruits[-4]) # applePython resolves a negative index by adding the list length to it. For a list of four items, -1 becomes 4 + (-1) = 3. The table shows both forms side by side.
| Item | Index | Negative index |
|---|---|---|
| apple | 0 | -4 |
| banana | 1 | -3 |
| cherry | 2 | -2 |
| date | 3 | -1 |
Use -1 for the last item instead of fruits[len(fruits) - 1]. It is shorter and works for any length.
The valid range
For a list of length n, the valid indices are -n through n - 1. That is 2n valid values, and each item has exactly one non-negative and one negative index. Anything outside that range raises IndexError.
fruits = ["apple", "banana", "cherry", "date"]
try:
print(fruits[4])
except IndexError as error:
print("Error:", error) # Error: list index out of range
try:
print(fruits[-5])
except IndexError as error:
print("Error:", error) # Error: list index out of rangeThe message does not say which index failed or how long the list was. When you debug, print both the index and len(items).
Empty lists
An empty list has no valid index at all. Even [][0] and [][-1] raise IndexError. This is a common source of crashes in code that reads "the first item" or "the last item" of a result that might be empty.
results = []
try:
print(results[-1])
except IndexError:
print("no results yet") # no results yetThe checks Python performs
Python checks the index type first, then the range, and then reads the item. A wrong type raises TypeError. An index outside the range raises IndexError.
Index types
An index must be an integer. A float fails even when its value is whole.
fruits = ["apple", "banana", "cherry", "date"]
try:
print(fruits[1.0])
except TypeError as error:
print("Error:", error)
# Error: list indices must be integers or slices, not float
print(fruits[True]) # bananaThe last line is a gotcha. bool is a subclass of int, so True acts as 1 and False acts as 0. Python accepts this silently. Avoid it on purpose, and treat it as a bug if you see it by accident. Any object that defines __index__, such as a NumPy integer, is also accepted. If you compute an index with /, you get a float. Use // to get an integer.
Guarding against a bad index
You have three common ways to deal with an index that may be out of range. The right one depends on whether a missing item is an error or a normal case.
- Let the exception happen. If the index should always be valid, a missing item is a bug, and a traceback is the right response.
- Check first. Test the length or the truthiness of the list before you read.
- Catch
IndexError. This suits code where the index comes from outside, such as user input.
def get_or_default(items, i, default=None):
"""Return items[i], or default if i is out of range."""
if -len(items) <= i < len(items):
return items[i]
return default
colors = ["red", "green"]
print(get_or_default(colors, 1)) # green
print(get_or_default(colors, 5)) # None
print(get_or_default(colors, -3, "?")) # ?
if colors: # an empty list is falsy
print("last color:", colors[-1]) # last color: greenUnlike dict.get, lists have no built-in "get with default". That is why a small helper like this one is common.
Negative indices wrap silently
Negative indexing is convenient, but it hides one kind of bug. If you compute an index with subtraction, a result that goes below zero does not raise an error. It wraps around to the end of the list.
scores = [10, 20, 30]
i = 0
print(scores[i - 1]) # 30, not an error: it reads the last itemSuppose you want "the previous item", and i is 0. There is no previous item, but scores[-1] returns the last one. The program keeps running with wrong data. When an index comes from arithmetic, check that it is >= 0 explicitly.
Assigning by index
You can put an index on the left side of = to replace an item. This changes the list in place, and the list length stays the same.
fruits = ["apple", "banana", "cherry", "date"]
fruits[0] = "avocado"
fruits[-1] = "dragonfruit"
print(fruits) # ['avocado', 'banana', 'cherry', 'dragonfruit']
try:
fruits[10] = "extra"
except IndexError as error:
print("Error:", error) # Error: list assignment index out of rangeIndex assignment cannot grow a list. To add an item, use append or insert, which later chapters cover.
An index returns the item itself, not a copy
items[i] returns a reference to the object stored in that slot. For immutable items such as numbers and strings, this makes no practical difference. For mutable items such as lists, the result is the same object that sits in the outer list.
rows = [[1, 2], [3, 4]]
first = rows[0] # a reference to the inner list, not a copy
first.append(99)
print(rows) # [[1, 2, 99], [3, 4]]Chaining indexes reads into nested lists. In rows[1][0], Python evaluates rows[1] first and then indexes the result with [0].
rows = [[1, 2], [3, 4]]
print(rows[1][0]) # 3
print(rows[-1][-1]) # 4Each index is checked separately. rows[1] can succeed and [5] on the inner list can still raise IndexError. A later chapter covers nested lists and the copying problems that come with them.
When you need the index and the item
Do not write range(len(items)) just to get both. Use enumerate, which yields (index, item) pairs.
fruits = ["apple", "banana", "cherry"]
for position, fruit in enumerate(fruits):
print(position, fruit)
# 0 apple
# 1 banana
# 2 cherry
for position, fruit in enumerate(fruits, start=1):
print(position, fruit) # numbers from 1, for display only
# 1 apple
# 2 banana
# 3 cherryThe start argument changes only the number that enumerate reports. It does not change how the list is indexed.
Common errors in review
| Symptom | Likely cause | Fix |
|---|---|---|
| `IndexError` on `items[len(items)]` | Off-by-one: the last index is `len(items) - 1` | Use `items[-1]` |
| `IndexError` on an empty list | Reading `items[0]` or `items[-1]` with no check | Test `if items:` first |
| `TypeError` about "integers or slices" | A float or string index | Convert with `int()` or use `//` |
| Wrong item, no error | A computed index went negative and wrapped | Check `i >= 0` before reading |
| A change to one list shows up in another | The item read was a shared mutable object | Copy it, as a later chapter shows |
Exercise
Given letters = ["a", "b", "c", "d", "e"], what do letters[-2] and letters[len(letters) - 2] return, and what does letters[5] do?
Show answer
Both letters[-2] and letters[len(letters) - 2] return "d". Python turns -2 into 5 + (-2) = 3, and index 3 holds "d". letters[5] raises IndexError because the valid range is -5 through 4.
Exercise
A function returns the previous reading with readings[i - 1]. It is called with i = 0 on the list [7, 8, 9]. What does it return, and how would you change the function so it does not return wrong data?
Show answer
It returns 9, because readings[-1] is the last item and Python raises no error. Add a check such as "if i < 1: return None" (or raise ValueError) before reading readings[i - 1].
Exercise
Write a function lastornone(items) that returns the last item of a list, or None if the list is empty. Do not catch an exception.
Show answer
def lastornone(items): if items: return items[-1] return None