Python Foundations · Lesson 8 of 12

Lists and indexing

List creation, traversal and updating. Learn through short examples, practical tasks and targeted questions.

← All lessons

Working with lists

A list groups related values in an ordered sequence. The first element has index 0; loops can visit each element to total values, search for a match or update the contents. Trace the index and value separately when using a counted loop.

Watch out: The final valid index is len(items)-1. Attempting items[len(items)] raises an IndexError.

1 · Understand

List creation, traversal and updating. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

scores = [7, 9, 6]
scores.append(8)
for score in scores:
    print(score)
Download example .py ↓

2 · Practise

Ask for five scores, store them in a list, and display the highest without using max().

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
scores = []
for i in range(5):
    scores.append(int(input("Score: ")))
highest = scores[0]
for value in scores:
    if value > highest:
        highest = value
print("Highest:", highest)
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

items = ["a", "b"]
print(items[2])
Reveal the corrected program and explanation
items = ["a", "b"]
print(items[1])

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

What is the index of the first element in a Python list?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

Indexes start at zero in Python. When tracing a list operation, write the index above each item and note whether a method changes the original list or produces a new value.

Quick check: What does items[-1] access?

Check: The last element in the list, provided the list is not empty.