Skip to content

Lesson 6 of 52Collections

Lists

Create, slice, change and copy lists, avoid aliasing bugs, and know which list operations are fast or slow.

16 min read0/4 questions

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.

Python
scores = [88, 92, 75]names = ["Ada", "Sam"]empty = []mixed = [1, "two", 3.0, None] print(len(scores), scores[0], scores[-1])print(92 in scores)print(list("abc"))
Output
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".

Slicing nums = [10, 20, 30, 40, 50, 60]
10
0
20
1
30
2
40
3
50
4
60
5

nums[1:4] is [20, 30, 40]: start at index 1, stop before index 4.

1/5

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.

Predict the outputPython

What does this print?

letters = ["a", "b", "c", "d", "e"]
print(letters[1:3])
print(letters[-3:])
Need a nudge? Hints walk you through it.

Changing a list

Lists are mutable: you can change them after creating them. These methods change the list in place:

MethodWhat 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] = xreplace the item at i
Python
todo = ["write tests", "fix bug"]todo.append("deploy")todo.insert(0, "coffee")done = todo.pop(1)todo[0] = "more coffee"print(todo)print("Finished:", done)
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.

Python
nums = [3, 1, 2]print(sorted(nums), nums) # new list; original unchanged result = nums.sort()print(result, nums) # None; nums itself is now sorted
Output
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].

Python
grid = [ [1, 2, 3], [4, 5, 6],]print(grid[1][2]) # row 1, column 2grid[0][0] = 99print(grid)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
What does this print?
grid = [[0] * 2] * 2
grid[0][0] = 1
print(grid)
Need a nudge? A hint rules out a wrong answer.

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.

Aliases vs copies
a = [1, 2, 3]
NamesObjects in memoryalist[1, 2, 3]

One list object, one name.

1/5

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.

Python
import copy grid = [[1, 2], [3, 4]]shallow = grid.copy()deep = copy.deepcopy(grid) shallow[0][0] = 99print(grid) # changed! the inner list is sharedprint(deep) # untouched
Output
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.

OperationCostWhy
nums[i], nums[i] = xO(1)jump straight to position i
nums.append(x), nums.pop()O(1) amortizedusually 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 the pairs0/4 matched

Match each operation on a list of n items to its cost.

Choose an item, then its match on the other side.
ChallengeEasy

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([])            →  []
Python
def running_total(nums: list[int]) -> list[int]: # Keep a total as you walk the list. pass
ChallengeEasy

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]
Python
def flatten_once(rows: list[list]) -> list: # append or extend? One of them adds the items, one adds the list. pass
Key terms
slice
nums[start:stop:step] returns a new list; start included, stop excluded.
append vs extend
append adds one item (even a list). extend adds each item of an iterable.
sort vs sorted
.sort() sorts in place and returns None; 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.deepcopy copies all the way down.
amortized O(1)
Constant time on average across many calls, even if an occasional call is slow (like append resizing).