Reading a Traceback

~9 mindebugging

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

Examples

Returns the final item instead of raising IndexError

Input
last_item([1, 2, 3])
Output
3

A single-item list returns that item

Input
last_item([42])
Output
42

Works on strings as well as numbers

Input
last_item(["a", "b"])
Output
"b"

Hints

Hint 1

Work directly with the arguments and return the result rather than printing it.

Hint 2

Watch for this: still off by one.

Requirements

  • : a non-empty list

  • Return the final item.

Constraints

  • Standard library only, no imports required

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~9 min

3 employers weight this skill

2 frontier labs, 1 AI product company. Top match scores 80.

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)]
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.