← Back

Home β€Ί Problems β€Ί Negative indexing

Negative indexing

🧠 Predict the output Topic: lists Difficulty: easy Free

What this problem practises

Lists are mutable and assigned by reference. That one fact explains most list bugs: aliasing between what look like "copies", append() and sort() returning None, and slice boundaries that disagree with the index arithmetic.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

colors = ["red", "green", "blue", "yellow"]
print(colors[-1])
print(colors[-2])
print(colors[0])

Understand the rule

Negative indexes count from the end: items[-1] is the last element, items[-2] the second-to-last, and for a list of length n, items[-n] circles back to the first. There is no items[-0] β€” that is just items[0]. Predicting negative-index snippets is a translation exercise: convert each negative index to its positive twin (n + index) and read off the value.

How to trace it

  1. Write the list with both index rows: 0..n-1 on top, -n..-1 underneath.
  2. Translate each negative index with the formula: position = len(items) + negative_index.
  3. Check bounds after translating: items[-5] on a 3-item list is IndexError, exactly like items[2] on a 2-item list.
  4. In slices, translate before applying the half-open rule: items[-3:-1] takes two elements, not three.

Common wrong fixes

Rule to remember

A negative index is shorthand for len + index. Translate to positive positions first β€” then the ordinary indexing and slicing rules apply unchanged.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

Problem 3 of 20 in this path. Work them in order β€” each one builds on the rule before it.

← Previous problemNext in path: Slicing does not include the end index β†’

More lists problems

Keep going