Lesson 13 of 26 · about 15 min
Lists
A list holds many values in order, under one name. You can index it like a string, but unlike a string you can change it.
🧭 What you need first: Strings up close
A shopping list is one piece of paper with many items, in order. You can read item 3, add “milk” at the bottom, cross out “eggs,” or rewrite the whole thing alphabetically. It’s still the same piece of paper.
A Python list is that piece of paper. One name, many values, in a specific order, and you can change it. That’s the big difference from strings, which are welded shut.
Another way: a playlist
A playlist has songs in order. You can skip to song 0, add a song to the end, remove one, or shuffle. Tracks can repeat, and the playlist keeps its identity while its contents change.
Another way: a train
A train is a line of cars, each with a number starting at 0. You can attach a car at the end (append), uncouple the last one (pop), or swap what’s inside a car.
A list changing over time
Step through and watch the list grow, shrink and get sorted. Then edit the code and try .insert(0, "tea") or .remove("eggs").
Watch the code run, one step at a time
- 1shopping = ["eggs", "bread"]
- 2shopping.append("milk")
- 3shopping[0] = "oat milk"
- 4last = shopping.pop()
- 5shopping.sort()
- 6for item in shopping:
- 7 print("Buy", item)
- 8print(len(shopping), "items")
➜ yellow = the line about to run · ✓ = the line that just ran
The real words
A list is an ordered, mutable (changeable) sequence. It can hold any values, even mixed types or other lists: [1, "two", [3]].
| Operation | What it does |
|---|---|
lst[i], lst[a:b] |
read an item / make a new list from a slice |
lst[i] = x |
replace an item |
lst.append(x) |
add x to the end |
lst.insert(i, x) |
add x at position i |
lst.pop() / lst.pop(i) |
remove and return the last item / item i |
lst.remove(x) |
remove the first x found |
lst.sort() |
sort in place (changes lst, returns None) |
sorted(lst) |
return a new sorted list (lst unchanged) |
lst.index(x), lst.count(x) |
where is x? how many xs? |
sum, min, max, len |
totals and extremes |
x in lst |
is x in the list? |
lst + other, lst * 3 |
join lists / repeat |
Strings ↔ lists: "a,b,c".split(",") → ["a", "b", "c"], and ",".join(["a", "b"]) → "a,b". list("hi") → ["h", "i"].
⚠️ lst.sort() returns None. Writing lst = lst.sort() throws your list away. Use lst.sort() on its own line, or lst = sorted(lst).
Class statistics
Write average(nums) that returns the mean of a list of numbers (0 for an empty list). Then write above_average(nums) that returns a new list of the numbers greater than the average, in their original order.
Find the second biggest
Write second_largest(nums) that returns the second-largest distinct value, e.g. [4, 9, 9, 2] → 4. You may assume there are at least two different values.
nums = [3, 1, 2]. After nums = nums.sort(), what is nums?
Got it?
Finish the lesson to color it in on your map and collect its concept cards.
Did this lesson click?