List Indexing and Access

SA
StudyAI
AI-generated study notes
· Published Updated

From the PYTHON curriculum

TL;DR

Python lists are ordered collections of items, and you access individual items using their position, called an index. Indexes start counting from zero for the first item and can also be negative to count from the end. Understanding indexing lets you pinpoint and retrieve any element in your list efficiently.

1. The Mental Model

Imagine a row of numbered mailboxes, starting from zero. Each mailbox holds an item. To get an item, you just need to know its mailbox number (its index).

2. The Core Material

Lists in Python are like containers that hold a sequence of different items. Each item in the list has a specific position, and that position is called its index.

Indexing from the Start (Positive Indexes)

Magnifying glass emphasizing the index of a book, symbolizing research and focus.
Photo by Nothing Ahead on Pexels

Python uses zero-based indexing. This means the very first item in a list is at index 0, the second item is at index 1, and so on.

my_list = ["apple", "banana", "cherry", "date"]
# Indexes:    0         1         2         3

To access an item, you put its index in square brackets [] right after the list's name:

first_item = my_list[0]   # This gets "apple"
third_item = my_list[2]   # This gets "cherry"

Indexing from the End (Negative Indexes)

Magnifying glass emphasizing the index of a book, symbolizing research and focus.
Photo by Nothing Ahead on Pexels

Sometimes it's easier to count from the end of the list. Python lets you do this with negative indexes.

  • -1 refers to the last item.
  • -2 refers to the second to last item.
  • And so on.
last_item = my_list[-1]  # This gets "date"
second_to_last = my_list[-2] # This gets "cherry"

What Happens If You Go Out of Bounds?

Close-up of a pen and 'While You Were Out' message pad, emphasizing office communication.
Photo by Jason Deines on Pexels

If you try to access an index that doesn't exist (either too high or too low), Python will give you an IndexError.

# my_list has 4 items, so valid positive indexes are 0, 1, 2, 3
# Valid negative indexes are -1, -2, -3, -4
# Trying to access my_list[4] or my_list[-5] will cause an IndexError.

Here's how list indexing works:

graph TD
    A["Start"] --> B["Do you know the item's position?"];
    B -- "Yes, from the beginning" --> C["Use positive index (0, 1, 2...)"];
    B -- "Yes, from the end" --> D["Use negative index (-1, -2, -3...)"];
    C --> E{"Is the index within the list's bounds?"};
    D --> E;
    E -- "Yes" --> F["Return the item at that index"];
    E -- "No" --> G["Raise an IndexError"];
    F --> H["End"];
    G --> H;

3. Worked Example

Let's say you have a list of daily temperatures for a week and you want to get specific ones.

weekly_temps = [20, 22, 19, 23, 21, 24, 20] # Monday to Sunday
# Indexes:        0   1   2   3   4   5   6
# Negative:      -7  -6  -5  -4  -3  -2  -1

# Get Tuesday's temperature (second day)
tuesday_temp = weekly_temps[1]
print(f"Tuesday's temperature: {tuesday_temp}°C") # Output: Tuesday's temperature: 22°C

# Get Sunday's temperature (last day)
sunday_temp = weekly_temps[-1]
print(f"Sunday's temperature: {sunday_temp}°C") # Output: Sunday's temperature: 20°C

# Get Friday's temperature (third from the end)
friday_temp = weekly_temps[-3]
print(f"Friday's temperature: {friday_temp}°C") # Output: Friday's temperature: 21°C

# What if we try to get a temperature that doesn't exist?
try:
    non_existent_day = weekly_temps[7] # There's no index 7 in a 7-item list
except IndexError as e:
    print(f"Error: {e}") # Output: Error: list index out of range

4. Key Takeaways

  • Lists are ordered collections, meaning items maintain their position.
  • You access individual items in a list using their index.
  • Indexes start counting from 0 for the first item (positive indexing).
  • You can count from the end of the list using negative indexes, where -1 is the last item.
  • Using an index that doesn't exist in the list will cause an IndexError.
  • Lists are mutable, but indexing is just for access; changing items requires assignment.
  • Indexing is a fundamental skill for working with sequences in Python.

Common Mistakes to Avoid

Flat lay of a spiral notebook and eraser on a pastel pink background with crossed out words.
Photo by KATRIN BOLOVTSOVA on Pexels

  • Forgetting zero-based indexing: Always remember that the first item is at index 0, not 1.
  • Off-by-one errors: Accidentally using len(my_list) as the last index instead of len(my_list) - 1 (or -1).
  • Ignoring IndexError: Not handling cases where an index might be out of bounds, especially with user input or dynamic lists.
  • Confusing list with other types: Indexing works for other sequence types (like strings, tuples) but not for unordered collections like sets or key-value pairs like dictionaries.

5. Now Try It

Create a list called favorite_colors with at least five different colors. Then, write Python code to:
1. Print the second color in your list.
2. Print the last color in your list using a negative index.
3. Try to access an index that you know is out of bounds (e.g., favorite_colors[100]) and observe the error.

Success looks like: Your code runs without errors for the first two parts, correctly printing the colors, and then explicitly shows an IndexError for the third part, demonstrating you understand index boundaries.

Frequently asked about List Indexing and Access

Python lists are ordered collections of items, and you access individual items using their position, called an index. Indexes start counting from zero for the first item and can also be negative to count from the end. Read the full notes above for the details.

List Indexing and Access is a core topic in PYTHON. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.
Continue with
Iterating Through Lists

Study this next


Get the full PYTHON curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Save this course free