Python Lists: Order, Indexing, Slicing, and Shared Mutability
Store ordered items in Python lists, grab values with negative indexes and slices, and avoid the shared-reference bug when copying lists.
You'll learn how Python lists store ordered items, how positive/negative indexing and slicing work, and why b = a on a list doesn't actually copy it. Assumes Python 3 installed.
1. A list keeps things in order
A list is an ordered sequence wrapped in square brackets []. Python counts positions starting at 0, and negative numbers count backward from the end (-1 is the last item):
moods = ["hopeful", "confused", "caffeinated", "done"]
print(moods[0])
print(moods[-1])
print(len(moods))hopeful
done
4Asking for an index that doesn't exist (moods[10]) raises IndexError: list index out of range.
2. Slicing sublists with [start:stop]
Slicing extracts a brand-new list from start up to (but not including) stop:
nums = [10, 20, 30, 40, 50]
print(nums[1:4])
print(nums[:2])
print(nums[::-1])[20, 30, 40]
[10, 20]
[50, 40, 30, 20, 10]3. Changing lists (and the copy trap)
Lists are mutable—you can change them in place with .append(x), .pop(), and .remove(x):
a = ["hope"]
b = a
a.append("despair")
print(b)['hope', 'despair']Surprise: b changed too! Remember that variables are name tags, not boxes. b = a attached a second name tag to the exact same list. If you actually want an independent copy, write b = a.copy() (or b = a[:]).
Try b = a.copy(), then a.append("coffee"), and print b to confirm b stays unchanged.
Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
IndexError: list index out of range | Index is >= len(list) | Check len(items) or use negative index -1 |
result = items.sort() gives None | .sort() changes the list in place and returns None | Use sorted(items) to get a new sorted list |
Mutating b accidentally changes a | b = a shares the same list | Use b = a.copy() |
Practice
- Given
letters = ["a", "b", "c", "d"], what doesletters[-2:]return?
Answer: ['c', 'd'].
What you learned
- Lists are ordered, zero-indexed, and support negative indexing (
-1for last) and[start:stop]slicing. - Lists are mutable;
b = ashares the same list, whereasb = a.copy()makes a separate copy. .sort()mutates in place and returnsNone;sorted(items)returns a new list.