Introduction to Computer Science/5.2 Accessing List Items with Indexes

5.2 Accessing List Items with Indexes

🎯 Learning Goals for This Page
  • Define "index" as an item's position in a list.
  • Explain and apply Python's "zero-based indexing" system.
  • Use square bracket syntax [index] to retrieve a single item from a list.
  • Use negative indexing to access items from the end of a list.

Getting Items Out of Your List

A list isn't useful if you can't access the items inside it. To get a specific item, you need to know its position, or index. Think of a list like a row of mailboxes: each mailbox holds an item, and each has a number on the front so you know which one to open.

⚠️ The Golden Rule: Counting Starts at Zero!

In Python (and most other programming languages), the first item in a list is at index 0, the second item is at index 1, and so on. This is called zero-based indexing. It's the most important and sometimes trickiest rule to remember about lists.

Here's how the indexes map to the items in a list:

avengers = ["Iron Man", "Captain America", "Thor", "Hulk"]
# Index:      0             1                2        3

The Syntax: list_name[index]

To get an item, you type the name of the list followed by the index you want in square brackets.

  • To get the first item: avengers[0] (which is "Iron Man")
  • To get the third item: avengers[2] (which is "Thor")

A Handy Shortcut: Negative Indexing

Python has a great shortcut for accessing items from the end of the list. The index -1 refers to the last item, -2 refers to the second-to-last, and so on.


Knowledge Check: Test Your Indexing Skills!

Before you experiment with the live code, let's do a quick knowledge check to see if you've mastered zero-based indexing. Try the interactive quiz below.

Note

Live Example: Accessing Your Heroes

The Trinket below demonstrates how to access list items using both positive and negative indexes. Run the code, then follow the "Your Turn" instructions printed at the end to experiment with different indexes and see what happens when you go out of bounds!

Python 3Initializing...
Loading code editor...
Program output will appear here...
The `IndexError`

If you try to access an index that doesn't exist (like avengers[4] in our example), your program will crash with an IndexError. This is a very common bug, and it's your first clue that you've tried to access an invalid position in your list.

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...