Python list exercises
Lists look simple until a loop runs one step too far or two variables turn out to be the same list. These exercises are short functions that work with lists, each with one real bug and tests that prove your fix.
They cover what trips beginners most: indexes and slices, methods that change the list and return None, and copies that are not copies.
The lists bugs you will meet
- The last index is len(items) - 1, and a slice's end is never included.
- append() and sort() change the list and return None, so items = items.sort() loses everything.
- b = a does not copy a list; both names point at the same one.
- Removing items while looping over the same list skips elements.
- [[0] * 3] * 3 makes three references to one row.
The exercises
Easy
Medium
Hard
- Binary search can't find the last itemOff-by-one
- Two shoppers end up with the same basketScope and closure
- Removing even numbers leaves one behindMutation and copying
- New basket already has the first basket's itemScope and closure
- Splitting into groups loses the last groupOff-by-one
- Best window of 2 misses the last pairOff-by-one
- Editing a copied grid changes the originalMutation and copying
Errors you might be searching for
More Python practice by topic
Questions
Do I need to know loops first?
Basic for loops help. If you are newer than that, start with the easy ones at the top: several need no loop at all.
Is there a certificate?
Yes, free. Fixing 25 easy Python bugs while signed in earns Python Debugging · Level 1, and the 30-day Python path has its own certificate.