Python IndexError · Exercises
Core Python

Python IndexError Exercises

4 exercises that build on the Python IndexError: list index out of range lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: An IndexError happens when you ask a list, tuple or string for a position that doesn't exist, such as item 3 of a list that only has items 0, 1 and 2. By the end you can explain why an index is out of range, recognise the usual causes (off-by-one loops, empty lists, pop() on an empty list, short strings) and fix each one. You will practise: Fix the last song; Predict the indexes; First and last, safely; Day-to-day changes.

0 / 4 completed

Python IndexError practice exercises

1. Fix the last song

Fix the bug Easy

This code should store the last song of the playlist in last_song and print it, but it raises an IndexError. Fix it so it still works if songs are added to or removed from the playlist.

Your code
playlist = ["Intro", "Song A", "Song B", "Outro"]
last_song = playlist[len(playlist)]
print("Last song:", last_song)

2. Predict the indexes

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to compare.

Read this code
letters = ["a", "b", "c"]
print(letters[-3])
print(letters[1:5])

try:
    print(letters[3])
except IndexError:
    print("no index 3")

print(len(letters[3:]))

3. First and last, safely

Write code Medium

Write first_and_last(items) that returns a tuple (first, last) with the first and last item of the list. If the list is empty, return (None, None) instead of raising an IndexError.

Your code
def first_and_last(items):
    # return (first item, last item), or (None, None) for an empty list
    pass

print(first_and_last([4, 8, 15]))
print(first_and_last([]))

4. Day-to-day changes

Write code Hard

Write differences(values) that returns a list of the changes between each value and the one after it. For [3, 7, 12, 10] the result is [4, 5, -2] (7-3, 12-7, 10-12). A list with fewer than two values has no changes, so return []. Careful: comparing each item with the next one is a classic place for an off-by-one IndexError.

Your code
def differences(values):
    changes = []
    # compare each value with the one after it
    return changes

print(differences([3, 7, 12, 10]))

Next lessonPython NameError

More Python IndexError: list index out of range examples · All Python exercises