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
- Write the list with both index rows: 0..n-1 on top, -n..-1 underneath.
- Translate each negative index with the formula: position = len(items) + negative_index.
- Check bounds after translating: items[-5] on a 3-item list is IndexError, exactly like items[2] on a 2-item list.
- In slices, translate before applying the half-open rule: items[-3:-1] takes two elements, not three.
Common wrong fixes
- Treating -1 as the first element (mirroring 0) when it is the last.
- Expecting negative indexes to be crash-proof; out-of-range negatives raise IndexError just like positives.
- Forgetting that in slices the stop is still excluded: [-3:-1] stops before the last element.
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.
π¦ 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
- List multiplication medium
- Looping one step too far easy
- List slicing with step medium
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every lists problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.