Sub topic 2
Lists: ordered collections you can change
This chapter covers the working model of list, the operations you will use daily, and the errors that most often trip people up. It assumes you know basic Python syntax (variables, loops, functions), the built-in types int, str, and bool, and how to run Python 3 in a REPL or script. It also assumes you have read the previous chapter on mutable and immutable objects.
The working model
A list is an ordered, mutable sequence. Three properties follow from that definition:
- Ordered means each element has a fixed position, called an index, starting at 0. The order is the order you put the elements in. Python does not reorder a list on its own.
- Mutable means you can change the list object itself: add elements, remove them, replace them, or reorder them. The list keeps the same identity (the same object in memory) while its contents change.
- Sequence means you can index it, slice it, take its length with
len, and loop over it in order.
A list can hold any objects, including a mix of types and other lists. Duplicates are allowed.
Internally, a CPython list is a resizable array of references. Each slot holds a pointer to an object, not the object itself. This explains two things you will see later: indexing is fast, and copying a list copies the pointers, not the objects they point to.
scores = [90, 85]
scores.append(77)
scores[0] = 95
print(scores) # [95, 85, 77]
point = (3, 4)
try:
point[0] = 1
except TypeError as e:
print(e) # 'tuple' object does not support item assignmentThe list accepts both changes. The tuple rejects the assignment. That contrast is the main reason to pick one over the other, and the next chapter covers tuples in detail.
Creating lists
There are four common ways to build a list.
empty = []
literal = [1, 2, 3]
from_iterable = list("abc") # ['a', 'b', 'c']
comprehension = [n * n for n in range(5)] # [0, 1, 4, 9, 16]
print(empty, literal, from_iterable, comprehension)list(x) accepts any iterable and builds a new list from it. This is also how you make a shallow copy: list(other) returns a new list holding the same elements.
A list comprehension builds a list from a loop and an optional filter in a single expression. Use it when you are transforming or filtering. Use a plain loop when the body has side effects or several steps.
words = ["apple", "fig", "banana", "kiwi"]
short = [w.upper() for w in words if len(w) <= 4]
print(short) # ['FIG', 'KIWI']Indexing and slicing
Indexes count from 0 at the front. Negative indexes count from the end, so -1 is the last element.
letters = ["a", "b", "c", "d", "e"]
print(letters[0]) # a
print(letters[-1]) # e
print(letters[1:4]) # ['b', 'c', 'd']
print(letters[:2]) # ['a', 'b']
print(letters[::2]) # ['a', 'c', 'e']
print(letters[::-1]) # ['e', 'd', 'c', 'b', 'a']A slice letters[start:stop:step] includes start and excludes stop. A slice always returns a new list, and an out-of-range slice does not raise an error. A single out-of-range index does.
letters = ["a", "b", "c"]
print(letters[1:100]) # ['b', 'c']
try:
letters[100]
except IndexError as e:
print(e) # list index out of rangeYou can also assign to a slice. The replacement does not need to be the same length, so the list can grow or shrink.
nums = [1, 2, 3, 4, 5]
nums[1:3] = [20, 30, 40]
print(nums) # [1, 20, 30, 40, 4, 5]
nums[1:4] = []
print(nums) # [1, 4, 5]Changing a list
The most common methods fall into three groups.
| Goal | Method | Notes |
|---|---|---|
| Add one element at the end | `append(x)` | Fast |
| Add several elements at the end | `extend(iterable)` | Same as `+=` with an iterable |
| Insert at a position | `insert(i, x)` | Shifts later elements |
| Remove by value | `remove(x)` | Removes the first match; raises `ValueError` if missing |
| Remove by position | `pop(i)` | Returns the element; default is the last |
| Remove by position or slice | `del lst[i]` | Returns nothing |
| Remove everything | `clear()` | Empties the same object |
| Sort in place | `sort()` | Returns `None` |
| Reverse in place | `reverse()` | Returns `None` |
Methods that change a list in place return None. This is a deliberate design choice. It signals that the original object changed and that you did not get a new one.
queue = [10, 20]
queue.append(30)
queue.extend([40, 50])
queue.insert(0, 5)
print(queue) # [5, 10, 20, 30, 40, 50]
last = queue.pop()
first = queue.pop(0)
print(last, first) # 50 5
queue.remove(20)
print(queue) # [10, 30, 40]
result = queue.sort()
print(result) # Noneappend versus extend
append adds its argument as one element. extend adds each element of its argument. Mixing them up is a frequent mistake.
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4]Sorting
list.sort() sorts in place and returns None. The built-in sorted() accepts any iterable and returns a new sorted list, leaving the original alone. Both take a key function and a reverse flag. Both are stable, which means elements that compare equal keep their original relative order.
people = [("Ana", 31), ("Ben", 27), ("Cy", 31)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age) # [('Ben', 27), ('Ana', 31), ('Cy', 31)]
by_age_desc = sorted(people, key=lambda p: p[1], reverse=True)
print(by_age_desc) # [('Ana', 31), ('Cy', 31), ('Ben', 27)]Stability is useful. To sort by two criteria, you can sort by the secondary one first and then by the primary one.
Sorting needs the elements to be comparable with each other. A list that mixes int and str raises TypeError when sorted.
Identity, aliasing, and copying
Assigning a list to another name does not copy it. Both names refer to the same object.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # TrueTo get an independent list, copy it. All of these make a shallow copy:
a = [1, 2, 3]
c1 = a.copy()
c2 = list(a)
c3 = a[:]
c1.append(99)
print(a) # [1, 2, 3]
print(c1) # [1, 2, 3, 99]A shallow copy duplicates the outer list only. If the elements are themselves mutable, the copy and the original share them.
import copy
grid = [[0, 0], [0, 0]]
shallow = grid.copy()
shallow[0][0] = 1
print(grid) # [[1, 0], [0, 0]]
deep = copy.deepcopy(grid)
deep[1][1] = 7
print(grid) # [[1, 0], [0, 0]]
print(deep) # [[1, 0], [0, 7]]copy.deepcopy copies the nested objects as well. It is slower and can surprise you with custom objects, so use it only when you need it.
The repetition trap
The expression [[0] * 3] * 2 does not build two separate rows. The * operator repeats the reference, so both rows are the same list.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0]]Repetition is fine for immutable elements such as numbers and strings. Use a comprehension when the elements are lists, dicts, or other mutable objects.
Changing a list while looping over it
Removing or inserting elements while iterating over the same list makes the iterator skip items, because the indexes shift under it.
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 2, 3] (the second 2 was skipped)Build a new list instead, or iterate over a copy.
nums = [1, 2, 2, 3, 4]
odds = [n for n in nums if n % 2 != 0]
print(odds) # [1, 3]
for n in nums[:]: # loop over a copy
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 3]Assigning to existing positions during a loop is safe, because the length does not change. Only insertions and removals cause trouble.
Cost of common operations
A list is an array of references, so operations that touch the end are cheap and operations that touch the front or the middle are not.
| Operation | Typical cost |
|---|---|
| `lst[i]`, `lst[i] = x` | Constant time |
| `append(x)`, `pop()` | Constant time on average |
| `insert(i, x)`, `pop(i)`, `del lst[i]` | Linear in the elements after `i` |
| `x in lst`, `lst.index(x)`, `lst.count(x)` | Linear: checks elements one by one |
| `sort()` | About n log n |
| Slice `lst[a:b]` | Linear in the slice length |
The row that matters most is x in lst. It compares x against each element until it finds a match, so a membership test on a large list is slow when you repeat it. If you test membership many times, convert the list to a set once. A later chapter compares these costs in detail.
pop(0) and insert(0, x) shift every other element. If you use a list as a queue and remove from the front often, collections.deque is built for that. The last chapter covers it.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `IndexError: list index out of range` | Index at or beyond `len(lst)`, or the list is empty | Check `len`, use a slice, or test `if lst:` |
| `ValueError: list.remove(x): x not in list` | Removing a value that is absent | Test with `in` first, or catch `ValueError` |
| `lst` becomes `None` | Assigned the result of `sort()`, `append()`, or `reverse()` | Call the method without assigning, or use `sorted()` |
| Changing one row changes all rows | `[[0] * n] * m` | Use a comprehension |
| Original list changed after "copying" | Plain assignment `b = a` | Use `a.copy()` or `list(a)` |
| Items skipped in a loop | Removing while iterating | Build a new list or loop over a copy |
| `TypeError: '<' not supported between instances` | Sorting mixed incomparable types | Convert, or pass a `key` function |
When a list is the right choice
Choose a list when:
- the order of elements matters and you need to read them by position;
- the collection grows, shrinks, or is rearranged while the program runs;
- duplicates are meaningful;
- the elements are all the same kind of thing, such as a list of scores or file names.
Look elsewhere when you mostly ask "is this value present?" (a set), when you look values up by a name or identifier (a dict), or when the collection is a fixed record of different fields (a tuple). A list also cannot be a dict key or a set element, because it is mutable and therefore unhashable. The hashability chapter explains why.
Worked example: grouping and cleaning data
This example combines slicing, comprehensions, sorting with a key, and safe copying. It cleans a list of raw readings, keeps the original intact, and reports the top three values.
raw = ["12", " 7", "x", "30 ", "7", "19", ""]
def clean(values):
out = []
for v in values:
v = v.strip()
if v.isdigit():
out.append(int(v))
return out
readings = clean(raw)
print(readings) # [12, 7, 30, 7, 19]
top_three = sorted(readings, reverse=True)[:3]
print(top_three) # [30, 19, 12]
backup = readings.copy()
readings.sort()
print(readings) # [7, 7, 12, 19, 30]
print(backup) # [12, 7, 30, 7, 19]Notes on the choices: clean creates a fresh list on each call, so no state is shared between calls. sorted(...) leaves readings in its original order, and .copy() preserves that order before the in-place sort(). Duplicates (the two 7s) remain, which is the correct behavior for a list.
Exercise
What does this code print, and why? rows = [[0] * 2] * 2, then rows[0][1] = 5, then print(rows). How do you change the first line so only the first row is affected?
Show answer
It prints [[0, 5], [0, 5]]. The outer * repeats a reference to the same inner list, so both rows are one object. Build the rows separately with rows = [[0] * 2 for _ in range(2)], which gives [[0, 5], [0, 0]] after the assignment.
Exercise
You write names = ["bo", "al", "cy"] and then names = names.sort(). What is names afterward, and what are two correct ways to get a sorted list?
Show answer
names is None, because sort() sorts in place and returns None. Either call names.sort() on its own line to sort the existing list, or write names = sorted(names) to build a new sorted list.
Exercise
A loop removes every even number from nums = [2, 4, 6, 7] using for n in nums: if n % 2 == 0: nums.remove(n). The result is [4, 7], not [7]. Explain the cause and give a fix.
Show answer
Removing an element shifts the later ones one position left, but the loop's internal index still advances, so it skips the element that moved into the removed slot. Fix it by building a new list, nums = [n for n in nums if n % 2 != 0], or by looping over a copy with for n in nums[:].