Lesson 6 of 52Collections
Lists
Create, slice, change and copy lists, avoid aliasing bugs, and know which list operations are fast or slow.
So far each name has held one value, but real data comes in groups. The list is Python's workhorse. API responses, rows from a database, lines of a file, a queue of jobs: they all end up in lists. You will use them in nearly every program and every coding interview, so it pays to know them deeply: how slicing works, which methods change the list in place, and why b = a does not make a copy.
Making and reading lists
A list is an ordered, changeable collection written with square brackets. It can hold anything, including a mix of types, though in practice most lists hold one kind of thing.
Press Run (⌘ Enter) to see what happens.Indexing works exactly like strings: scores[0] is the first item, scores[-1] the last. in checks membership, and list(...) turns any iterable into a list.
Slicing
A slice pulls out a range: nums[start:stop:step]. Like range, the start is included and the stop is not. Leave a part out to mean "from the beginning", "to the end" or "every item".
nums[1:4] is [20, 30, 40]: start at index 1, stop before index 4.
Slicing always returns a new list and never raises IndexError: nums[4:100] just gives you what exists. That makes it safe for "first 10 results" code even when there are fewer than 10.
What does this print?
letters = ["a", "b", "c", "d", "e"] print(letters[1:3]) print(letters[-3:])
Changing a list
Lists are mutable: you can change them after creating them. These methods change the list in place:
| Method | What it does |
|---|---|
nums.append(x) | add one item at the end |
nums.extend(other) | add every item of other at the end |
nums.insert(i, x) | add x at index i, shifting the rest right |
nums.pop() / nums.pop(i) | remove and return the last item, or the one at i |
nums.remove(x) | remove the first item equal to x (ValueError if missing) |
nums.sort() / nums.reverse() | reorder in place |
nums[i] = x | replace the item at i |
Press Run (⌘ Enter) to see what happens.append vs extend
append adds its argument as one item, even if that argument is a list. extend adds each item of its argument. Mixing them up is one of the most common list bugs.
What does this print?
a = [1, 2] a.append([3, 4]) b = [1, 2] b.extend([3, 4]) print(a, len(a)) print(b, len(b))
sort vs sorted
nums.sort() sorts the list in place and returns None. The built-in sorted(nums) leaves the original alone and returns a new sorted list. Both accept reverse=True.
Press Run (⌘ Enter) to see what happens.Writing nums = nums.sort() is a classic bug: it sorts the list, then throws it away and leaves nums as None. A general Python rule: methods that change an object in place return None.
Lists of lists
A list can hold other lists, which is how you represent a grid, a table or a game board. Index twice: grid[row][col].
Press Run (⌘ Enter) to see what happens.grid = [[0] * 2] * 2 grid[0][0] = 1 print(grid)
Aliasing and copying
Remember that = ties a name to an object and never copies. With mutable objects like lists, that matters a lot. Two names for one list are called aliases, and a change through one is visible through the other.
One list object, one name.
There is one more layer. .copy() is a shallow copy: it makes a new outer list, but the items inside are the same objects. For a list of numbers that is fine. For a list of lists, the inner lists are still shared. When you need fully independent nested data, use copy.deepcopy.
Press Run (⌘ Enter) to see what happens.How fast is each operation?
A Python list is a dynamic array: items sit side by side in memory, with some spare room at the end. That layout explains the costs. Big-O notation describes how the work grows with the list size n: O(1) means constant time no matter how big the list, O(n) means work proportional to its length.
| Operation | Cost | Why |
|---|---|---|
nums[i], nums[i] = x | O(1) | jump straight to position i |
nums.append(x), nums.pop() | O(1) amortized | usually spare room at the end |
nums.insert(0, x), nums.pop(0) | O(n) | every other item must shift over |
x in nums, nums.index(x) | O(n) | may have to check every item |
nums[a:b], nums.copy() | O(k) / O(n) | builds a new list of that size |
nums.sort() | O(n log n) | Timsort |
Amortized means "on average over many calls". Occasionally the list runs out of spare room and copies itself to a bigger block, but that happens so rarely that each append is constant time on average.
Match each operation on a list of n items to its cost.
Running total
Write running_total(nums) that returns a new list where each position holds the sum of everything up to and including that position.
running_total([1, 2, 3, 4]) → [1, 3, 6, 10]
running_total([]) → []Flatten one level
Write flatten_once(rows) that takes a list of lists and joins them into one list, in order. Only remove one level of nesting.
flatten_once([[1, 2], [3], [4, 5]]) → [1, 2, 3, 4, 5]
flatten_once([[[1, 2]], [3]]) → [[1, 2], 3]- slice
nums[start:stop:step]returns a new list; start included, stop excluded.- append vs extend
appendadds one item (even a list).extendadds each item of an iterable.- sort vs sorted
.sort()sorts in place and returnsNone;sorted()returns a new list.- alias
- Two names for the same mutable object. A change through one is visible through the other.
- shallow copy
- A new outer list whose items are the same objects as the original.
copy.deepcopycopies all the way down. - amortized O(1)
- Constant time on average across many calls, even if an occasional call is slow (like
appendresizing).