Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Reading a Traceback

~9 mindebugging

When Python hits something it cannot do, it stops and prints a traceback:

Traceback (most recent call last):
  File "main.py", line 3, in last_item
    return values[len(values)]
IndexError: list index out of range

Read it bottom up:

  • The last line is the error type and message. IndexError: list index out of range means you asked for a position that does not exist.
  • Above it is the exact line that failed, with its line number.
  • Above that is how you got there, most recent call last.
  • Most of a traceback is context. The bottom two lines are usually the whole story.

    This specific bug: a list of length 3 has indices 0, 1 and 2. So values[len(values)] is values[3], which is one past the end. Off-by-one errors at the end of a list are the single most common cause of IndexError.

    Your task:

    last_item is meant to return the final item of a list. It raises IndexError on every input. Fix it.

    Example Tests

    Returns the final item instead of raising IndexError

    Input: {"values":[1,2,3]}

    Expected: 3

    A single-item list returns that item

    Input: {"values":[42]}

    Expected: 42

    Works on strings as well as numbers

    Input: {"values":["a","b"]}

    Expected: "b"

    Python
    def last_item(values):
        """
        Return the last item of a list.
    
        This currently raises IndexError. Work out why and fix it.
    
        Args:
            values: a non-empty list
    
        Returns:
            The final item.
        """
        return values[len(values)]

    Run your code to see results

    ⌘↵ runs against the visible tests

    Loading docs…