Sub topic 2
Lists: ordered collections you can change
This chapter assumes you can write basic Python (variables, loops, functions), know the built-in types int, str, and bool, and can run Python 3 in a REPL or script. It also builds on the previous chapter's distinction between mutable and immutable objects.
The working model
A list is an ordered, mutable sequence. Ordered means each item keeps a position, counted from 0. Mutable means you can add, remove, or replace items without creating a new list. The list keeps the same identity throughout.
scores = [90, 85]
before = id(scores)
scores.append(77)
scores[0] = 95
print(scores) # [95, 85, 77]
print(id(scores) == before) # TrueThe id check shows that both changes happened inside one object. A tuple would raise a TypeError on the same assignment.
Creating and reading lists
empty = []
digits = list(range(5)) # [0, 1, 2, 3, 4]
letters = list("abc") # ['a', 'b', 'c']
mixed = [1, "two", 3.0] # items may have different types
print(letters[0], letters[-1]) # a c
print(digits[1:4]) # [1, 2, 3]Negative indexes count from the end. A slice such as digits[1:4] returns a new list and leaves the original alone. Reading an index that does not exist raises IndexError. Slices never raise it.
Changing a list
| Method | Effect | Returns |
|---|---|---|
| `append(x)` | Adds `x` at the end | `None` |
| `extend(iterable)` | Adds each item of the iterable | `None` |
| `insert(i, x)` | Inserts `x` before index `i` | `None` |
| `remove(x)` | Deletes the first item equal to `x`; raises `ValueError` if absent | `None` |
| `pop(i=-1)` | Deletes and returns the item at `i` | the item |
| `sort()` | Sorts in place | `None` |
Methods that mutate a list in place return None. A common mistake is writing nums = nums.sort(), which replaces your list with None.
nums = [3, 1, 2]
result = nums.sort()
print(result) # None
print(nums) # [1, 2, 3]
print(sorted([3, 1, 2], reverse=True)) # [3, 2, 1], a new listUse sorted() when you want a new list and want to keep the original.
append and extend behave differently when you give them a list:
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]append adds one item, even if that item is itself a list. extend adds the contents.
Assignment does not copy
Assigning a list to a second name gives you two names for one object. Changes through either name are visible through both.
original = [1, 2, 3]
alias = original
duplicate = original[:] # slice copy; list(original) also works
alias.append(4)
print(original) # [1, 2, 3, 4]
print(duplicate) # [1, 2, 3]A slice copy is shallow. It copies the outer list but not any lists inside it. A later chapter covers the problems this causes.
Cost in brief
Adding or removing at the end (append, pop()) is cheap. Working at the front is not, because every other item has to shift. insert(0, x) and pop(0) take time proportional to the list length. Checking x in items also scans the list from the start. A later chapter compares these costs with dicts and sets. If you need fast removal from the front, the deque type in the last chapter fits better.
Changing a list while looping over it
Removing items from a list during a for loop over that same list skips items, because the positions shift under the iterator.
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums) # [1, 2, 3], one 2 survivedBuild a new list instead:
nums = [1, 2, 2, 3]
without_twos = [n for n in nums if n != 2]
print(without_twos) # [1, 3]When a list fits
Choose a list when:
- the order of items matters;
- duplicates are allowed;
- you will add, remove, or replace items;
- you need to reach items by position.
A list is a poor fit when you look things up by a name or key (use a dict), or when each item must appear only once (use a set).
Exercise
What do items and result hold after this code runs? Why?
items = [5, 3, 4]
result = items.sort()
alias = items
alias.append(1)
Show answer
result is None, because sort() changes the list in place and returns None. items is [3, 4, 5, 1]. sort() reordered it to [3, 4, 5]. Then alias and items name the same list, so appending through alias changes what items shows.