Lists, tuples, dicts and sets
Real programs work with collections of data: a list of orders, a dictionary of settings, a set of tags. Python's four built-in collections cover almost everything.
| Type | Example | Ordered | Changeable | Duplicates |
|---|---|---|---|---|
list |
[1, 2, 2] |
✅ | ✅ | ✅ |
tuple |
(1, 2, 2) |
✅ | ❌ | ✅ |
dict |
{"a": 1} |
✅ (insertion order) | ✅ | Keys unique |
set |
{1, 2} |
❌ | ✅ | ❌ |
Lists
Lists are mutable: you can change them in place.
Copies vs references
Assigning a list to another variable does not copy it. Both names point to the same list:
List comprehensions
A comprehension builds a new list from another sequence in one readable line:
It's the same as a for loop that appends, but shorter and usually faster.
Tuples
A tuple is like a list that can't change. Use it for fixed groups of values, like coordinates or a database row:
Because they can't change, tuples can be used as dictionary keys and set members, and they signal "this data is fixed".
Dictionaries
A dict maps keys to values, like a real dictionary maps words to definitions. Looking up a key is instant, however big the dict:
Looping over a dict
Counting and grouping
Two patterns you'll write constantly:
Dict comprehensions
Sets
A set holds unique values, with very fast membership checks and set maths:
Nested data
Real data (like JSON from an API) is usually lists of dicts:
Practice
- Given
nums = [4, 8, 15, 16, 23, 42], build a list of the numbers greater than 10, doubled, using a comprehension. - Count how many times each letter appears in
"mississippi". - Two lists of students took two exams. Find who took both, and who took only the first.
- From the
productslist above, build a dict mapping each product name to its price.
1.After a = [1, 2]; b = a; b.append(3), what is a?
2.What does user.get("email", "none") return when there's no email key?
3.Which collection is best for checking quickly whether a username is already taken?