Learn · Run · Break · Fix
A learning series from A Wandering Mind
Eighteen interlinked lessons on strings, lists, files, exceptions, and dictionaries—with original explanations, runnable examples, real output, and supporting CPSC 1301K lectures.
>>> guide = { ... "lessons": 18, ... "modules": 5, ... "python": "3.10+" ... } >>> guide["goal"] = "understand it"
Indexing Lists and Measuring Length in Python
Creating a list gives several values one container, but useful programs must also be able to reach a particular item and understand how large the collection is. Python solves those jobs with indexes and the built-in len() function. In this lesson, you will retrieve items from the beginning and end of a list, connect valid indexes to list length, and learn how to avoid the most common out-of-range mistakes.
Every list item has a position
Python lists are ordered. When you write ["red", "green", "blue"], Python keeps those values in that sequence unless your program later changes it. Because the order is meaningful, Python can assign each position an integer index. An index is not a label stored inside the list. It is the position you use to ask Python for one item.
The first position is index 0, not index 1. That zero-based system is one of the first conventions new programmers must internalize. If a list contains four items, its positive indexes are 0, 1, 2, and 3. The number of items is four, but the largest valid positive index is three.
colors = ["red", "green", "blue", "gold"]
print(colors[0])
print(colors[2])
print(colors[-1])
red
blue
gold
The square brackets after the variable name mean “retrieve the item at this position.” colors[0] returns the first item. colors[2] returns the third item. The final line introduces Python’s negative indexes: -1 means the final item, -2 means the second item from the end, and so on.
Useful mental model: positive indexes count forward from the beginning starting at 0. Negative indexes count backward from the end starting at -1. Both refer to the same underlying ordered list.
Negative indexes are more than shorthand
You could reach the last element by first calculating the list’s length and subtracting one. That works, and we will do it shortly because it teaches an important relationship. But Python’s -1 index communicates the idea “last item” directly. It is often easier to read when that is what you really mean.
Negative indexes also stay useful when the list’s length changes. If a list grows from three items to thirty, items[-1] still means the last item. You do not need to know the final positive index in advance. The limit is the same in the other direction, however: a three-item list has valid negative indexes -1, -2, and -3. Asking for -4 goes beyond the list.
Measuring a list with len()
The built-in len() function returns the number of items in a collection. For a list, that means the number of elements currently stored in it. The result is an integer, so you can print it, compare it, save it in a variable, or use it as part of another calculation.
cities = ["Atlanta", "Savannah", "Columbus", "Macon"]
print(len(cities))
print(cities[len(cities) - 1])
4
Macon
The list contains four cities, so len(cities) returns 4. But index 4 would be outside the list because the positive indexes start at zero. Subtracting one converts the count into the final positive index: 4 - 1 becomes 3. That relationship—last positive index = length - 1—is worth remembering.
Indexes can feed calculations and decisions
Indexing is not useful only for printing one isolated value. A retrieved element behaves like the value stored at that position, so it can participate in normal Python expressions. A numeric item can be subtracted, compared, or formatted. A string item can be passed to a string method. The list is the container; indexing gives you access to one of the values inside it.
scores = [88, 91, 76, 95]
first = scores[0]
last = scores[-1]
difference = last - first
print(f"First: {first}")
print(f"Last: {last}")
print(f"Difference: {difference}")
First: 88
Last: 95
Difference: 7
The variables first and last contain integers retrieved from the list. Once retrieved, they behave like ordinary integers. The f-strings connect this lesson back to Lesson 1 on formatted strings: collections and strings are separate topics, but real programs quickly use them together.
Check whether a position can exist before using it
Sometimes your program knows that a list contains data because you created the contents yourself. Other times the list may be empty or its size may depend on input. In those situations, len() can help you avoid making a request that cannot succeed. The simplest example is checking that the length is greater than zero before asking for index 0.
queue = ["A12", "A13", "A14"]
count = len(queue)
print(f"There are {count} items.")
if count > 0:
print(f"Next item: {queue[0]}")
There are 3 items.
Next item: A12
The conditional is deliberately simple. If the list were empty, count would be zero and Python would skip the indexing line. Later lessons will give you additional patterns for loops, membership tests, and exception handling. For now, the key idea is that length tells you something about which positions are possible.
items[0]Valid only when the list contains at least one item.
items[-1]Directly expresses “the item at the end.”
len(items)Returns an integer count, not an index.
len(items) - 1Valid only for a non-empty list.
Common mistakes with indexes and length
List-indexing errors are useful because Python is explicit about what went wrong. The following failures were executed so the tracebacks reflect real Python behavior rather than invented examples.
planets = ["Mercury", "Venus", "Earth"]
print(planets[3])
Traceback (most recent call last):
File "/tmp/awm_lesson4/mistake1_out_of_range.py", line 2, in <module>
print(planets[3])
~~~~~~~^^^
IndexError: list index out of range
There are three items, but the valid positive indexes are 0, 1, and 2. Index 3 is one position beyond the end. This is the classic off-by-one error caused by confusing a count with the largest index.
planets = ["Mercury", "Venus", "Earth"]
print(planets["0"])
Traceback (most recent call last):
File "/tmp/awm_lesson4/mistake2_wrong_index_type.py", line 2, in <module>
print(planets["0"])
~~~~~~~^^^^^
TypeError: list indices must be integers or slices, not str
0 and "0" are different Python values. The first is an integer and can be used as a list index. The second is a string containing one character. Lists expect integer positions—or slices, which arrive later in this module—not string labels.
count = len(42)
print(count)
Traceback (most recent call last):
File "/tmp/awm_lesson4/mistake3_len_number.py", line 1, in <module>
count = len(42)
^^^^^^^
TypeError: object of type 'int' has no len()
len() works with objects that have a meaningful length, such as lists and strings. An integer is a single numeric value, not a collection whose number of elements Python can count. If you want the number of digits in a number, that is a different question and requires a different approach.
items = []
print(items[-1])
Traceback (most recent call last):
File "/tmp/awm_lesson4/mistake4_empty_list.py", line 2, in <module>
print(items[-1])
~~~~~^^^^
IndexError: list index out of range
Negative indexing does not create an item where none exists. An empty list has length zero and therefore has no valid positive or negative indexes. This is exactly the situation where checking len(items) > 0 before indexing can be useful.
Supporting classroom explanations
This page is original A Wandering Mind instructional material and is designed to stand on its own. The two CPSC 1301K lectures below provide short classroom-style reinforcement for accessing list elements and measuring a list’s length.
What it adds: a focused classroom walkthrough of how numbered positions let you retrieve individual elements from an ordered list.
What it adds: a concise explanation of len() and the relationship between a list’s item count and its usable index positions.
Try it yourself
Before running each exercise, predict the output. Indexing becomes much easier once you can look at a list and mentally map its positions without counting from one.
Exercise 1 · First, third, and last
Create animals = ["otter", "heron", "fox", "turtle"]. Print the first item, the third item, and the last item using indexes.
Show one answer
animals = ["otter", "heron", "fox", "turtle"]
print(animals[0])
print(animals[2])
print(animals[-1])
otter
fox
turtle
Exercise 2 · Connect length to the final index
Create values = [10, 20, 30, 40, 50]. Print its length, then retrieve the last item using len(values) - 1 rather than -1.
Show one answer
values = [10, 20, 30, 40, 50]
print(len(values))
print(values[len(values) - 1])
5
50
Exercise 3 · Guard an empty list
Start with messages = []. Use len() in an if statement so the program prints No messages yet. instead of trying to access index 0.
Show one answer
messages = []
if len(messages) > 0:
print(messages[0])
else:
print("No messages yet.")
No messages yet.
What you should carry into Lesson 5
You now have the two basic tools needed to navigate an ordered list: integer indexes retrieve specific positions, and len() tells you how many elements the list contains. Positive indexes begin at zero, negative indexes count backward from the end, and a request outside the valid range raises IndexError. You also know the important relationship between the count and the last positive position: len(items) - 1.
The next lesson changes the question from “Which value is here?” to “How do I replace or remove it?” Continue to Changing and Removing List Items, where the fact that lists are mutable becomes the central idea.
