Accessing Items by Index
Every item in a list sits at a numbered position called its index, and the numbering starts at 0. The first item is at index 0, the second at index 1, and the last item of a list with 4 items is at index 3. To read an item, write the list's name followed by the index in square brackets.
| Item | Mon | Tue | Wed | Thu |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |
| Negative index | -4 | -3 | -2 | -1 |
days = ["Mon", "Tue", "Wed", "Thu"]
print(days[0])
print(days[3])
first = days[0]
print(first + " starts the week")Output:
Mon Thu Mon starts the week
days[0] is an expression with a value, so it goes anywhere a value goes: inside print, on the right of an assignment, or joined to another string with +. The index can be a variable too: with i = 2, days[i] is "Wed".
Counting from the end
A negative index counts backwards from the end. Index -1 is the last item, -2 the one before it, and -4 is the first item of a 4-item list. This saves working out the length first: the last item is at -1 whether the list has 4 items or 4000.
days = ["Mon", "Tue", "Wed", "Thu"]
print(days[-1])
print(days[-4])
print(days[len(days) - 1])Output:
Thu Mon Thu
The third line shows the long way to reach the last item: the length is 4, the last index is 3, so len(days) - 1 lands on "Thu". Negative indexing does the same arithmetic for you.
Past the end
An index that names no item stops the program. A list of 3 items has indexes 0 through 2, so asking for index 3 raises an IndexError, and nothing after that line runs. The first print below succeeds and the second one ends the program.
colors = ["red", "green", "blue"]
print(colors[2])
print(colors[3])
print("done")Run, this program prints blue and then stops with a traceback whose last line is IndexError: list index out of range. The word done never prints. That message always means the number in the brackets was too large for the list, or too negative: index -4 on this 3-item list fails the same way. Section 4 shows how to check before asking.
Replacing an item
The same bracket form on the left of = writes a value into a position. The old item goes away and the new one takes its index; the list keeps its length. Press play and watch index 2 change.
planets = ["Mercury", "Venus", "Mars", "Jupiter"]
print("Before:", planets)
# Fix: Earth should be at index 2
planets[2] = "Earth"
print("After:", planets)
# Update the first planet
planets[0] = "MERCURY"
print("Final:", planets)Before: ['Mercury', 'Venus', 'Mars', 'Jupiter'] After: ['Mercury', 'Venus', 'Earth', 'Jupiter'] Final: ['MERCURY', 'Venus', 'Earth', 'Jupiter']
Index 2 held "Mars" and after the assignment it holds "Earth". The other 3 items stay where they were, and the final line shows index 0 replaced as well. Assigning to an index that doesn't exist, such as planets[4] on this 4-item list, raises the same IndexError as reading one.
Index plus loop
range(len(tasks)) produces 0, 1, 2 for a list of 3 items, exactly the valid indexes. Looping over that range gives you both the position and, through tasks[i], the item at it.
tasks = ["write", "test", "ship"]
for i in range(len(tasks)):
print(i, tasks[i])Output:
0 write 1 test 2 ship
What does this program print?
letters = ["p", "q", "r", "s"]
letters[1] = letters[-1]
print(letters)- ['p', 'q', 'r', 'q']
- ['p', 's', 'r', 's']
- ['s', 'q', 'r', 's']
- ['p', 'q', 's', 's']
The third item is at index 2
People count positions from 1 and Python counts indexes from 0, so the item a person calls third sits at index 2: subtract 1 from the position. Counting from the back needs no subtraction, because the last item is -1, the second to last is -2, and so on.
finishers = ["Kim", "Raj", "Tess", "Ola", "Bea"]
print(finishers[2])
print(finishers[-2])
print(finishers[4] == finishers[-1])Output:
Tess Ola True
On a list of 5 items, index -1 names the same item as index 4, and -3 matches 2: a negative index is the positive one minus the length. Forgetting the minus 1 reads the item next door to the one you wanted, and Python raises no error to warn you, because that neighbour sits at a valid index.
About this lesson
This section is part of the Lists: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.