Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
A shopping list, a map pin, a stamp album and a contact book: Python's four collections with real output, the KeyError and empty-set traps, and type hints that label a variable without locking it.
What you will learn
- Choose between a list, tuple, set and dict for a job
- Add, remove, look up and unpack values in each collection
- Avoid two traps: KeyError on a missing key and {} being an empty dict
- Write type hints like dict[str, int] and explain why Python does not enforce them
Before you start
- Python Data Types, Variables and Strings
So far each variable has held a single value. But a shopping cart has many items, and a student has many details. Python gives you four ways to hold many values in one variable, and once you know them, most Python code gets a lot easier to read.
Before any code, think about four things you already use:
- A shopping list on paper. Items sit in order, and you can add one or cross one off. That's a list.
- A pin on a map. Two numbers that belong together, which nobody should change. That's a tuple.
- A stamp album. You keep one of each, so a second copy adds nothing. That's a set.
- A contact book. You look up a name and get a number back. That's a dictionary.
A list keeps things in order
shopping = ["milk", "eggs", "bread"]
item_count = len(shopping)
unit_price = 2.50
shopping.append("cheese")
shopping.remove("bread")
total_cost = item_count * unit_price
print(shopping)
print("First item:", shopping[0])
print("Got milk?", "milk" in shopping)
print(f"Estimated cost: ${total_cost:.2f}")
['milk', 'eggs', 'cheese']
First item: milk
Got milk? True
Estimated cost: $7.50
append adds cheese at the end, and remove finds bread and takes it out. Positions start at 0, so shopping[0] is milk. in asks a yes or no question: is it inside?
Notice one thing. item_count was counted on line two, and it doesn't follow the list. It's still right here only because we added one item and removed one.
Reading and changing a list
colors = ["red", "green", "blue"]
print(colors[0], colors[-1])
print(colors[0:2])
colors[1] = "yellow"
colors.insert(0, "black")
last = colors.pop()
colors.sort()
print(colors)
print(last)
print(len(colors))
red blue
['red', 'green']
['black', 'red', 'yellow']
blue
3
-1 counts from the end, and [0:2] is a slice that stops before index 2. colors[1] = "yellow" replaces green. insert(0, ...) puts black at the front, pop() takes the last item out and hands it back, and sort() puts the list in order. A list keeps its order, allows repeats, and changes in place.
A tuple is a fixed group
point = (3, 4)
single = (7,)
print(point)
print(point[0], point[1])
print(len(point), type(single))
x, y = point
print(x, y)
days = ("Mon", "Tue", "Wed")
print(days[-1])
(3, 4)
3 4
2 <class 'tuple'>
3 4
Wed
Reading works just like a list. A tuple with one value needs that comma; without it, (7) is only a 7 in brackets. x, y = point is unpacking: 3 goes into x and 4 into y in one assignment. You'll see it a lot with coordinates or the red, green and blue values of a colour.
A tuple can't be changed
point = (3, 4)
point[0] = 10
print(point)
Traceback (most recent call last):
File "S01L05_Collections\tuple_error.py", line 2, in <module>
point[0] = 10
~~~~~^^^
TypeError: 'tuple' object does not support item assignment
That's the reason to use one. If values belong together and shouldn't change, like a location or a box size, a tuple protects them.
A set keeps one of each
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)
print(len(numbers))
numbers.add(4)
numbers.add(2)
print(numbers)
print(3 in numbers)
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(a & b)
tags = ["new", "sale", "new", "hot", "sale"]
print(sorted(set(tags)))
{1, 2, 3}
3
{1, 2, 3, 4}
True
{1, 2, 3, 4, 5}
{3}
['hot', 'new', 'sale']
Python keeps only one of each, so the length is 3, not 6. Adding 2 again does nothing, with no error. The pipe | is union (everything from both), and & is intersection (only what's in both).
The everyday use is the last line: set(tags) removes repeats, and since a set doesn't promise any order, sorted gives you back a tidy list. A set has no positions either, so numbers[0] isn't allowed. Whenever you hear "unique values", think of a set.
A dictionary looks up by key
student = {"name": "Alice", "age": 21}
print(student["name"])
print(student.get("age"))
print(student.get("grade"))
print(student.get("grade", "not set"))
student["grade"] = "A"
student["age"] = 22
print(student)
print(student.keys())
print(student.values())
print("name" in student)
student.pop("age")
print(student)
Alice
21
None
not set
{'name': 'Alice', 'age': 22, 'grade': 'A'}
dict_keys(['name', 'age', 'grade'])
dict_values(['Alice', 22, 'A'])
True
{'name': 'Alice', 'grade': 'A'}
You ask by key, not by position. get is the second way to ask; for a key that isn't there, it hands back None (nothing there), or the default you give it. Writing to a new key adds it; writing to an existing key replaces the value, because each key appears only once. in on a dict checks the keys, not the values, and pop removes a key with its value.
When a key is missing
student = {"name": "Alice", "age": 21}
print(student["name"])
print(student["grade"])
Alice
Traceback (most recent call last):
File "S01L05_Collections\dict_missing_key.py", line 3, in <module>
print(student["grade"])
~~~~~~~^^^^^^^^^
KeyError: 'grade'
The rule: if you're sure the key is there, use square brackets. If it might be missing, use get.
The empty set trap
empty_list = []
empty_tuple = ()
empty_dict = {}
empty_set = set()
wrong_set = {}
print(type(empty_list))
print(type(empty_tuple))
print(type(empty_dict))
print(type(empty_set))
print(type(wrong_set))
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
<class 'dict'>
Someone wanted a set and wrote {}. Python says dict, and nothing warns you. Empty curly braces are an empty dictionary; set() is an empty set.
Type hints: a label on a box
Think about a storage box with a label that says books. The label tells everyone what's meant to be inside without opening it. It doesn't lock anything, though; someone can still put shoes in. But anyone checking can compare the contents with the label and point out that shoes don't belong. A type hint is that label, on a variable.
name: str = "Alice"
age: int = 21
price: float = 2.50
fruits: list[str] = ["apple", "banana"]
point: tuple[int, int] = (3, 4)
tags: set[str] = {"new"}
scores: dict[str, int] = {"maths": 90, "art": 75}
print(name, age, price)
print(fruits, point, tags)
print(scores)
Alice 21 2.5
['apple', 'banana'] (3, 4) {'new'}
{'maths': 90, 'art': 75}
A colon and a type go between the name and the value. list[str] is a list of strings, tuple[int, int] two whole numbers, and dict[str, int] string keys with whole-number values.
Python doesn't enforce hints
age: int = "twenty-one"
scores: dict[str, int] = {"maths": "high"}
print(age)
print(scores)
print(type(age))
twenty-one
{'maths': 'high'}
<class 'str'>
No error. The value decides the type, not the hint. Hints are there for people and tools: you, when you come back to the code later; PyCharm, which can warn you about a value that doesn't match and suggest the right methods; type checkers that read a whole project; and AI tools, which read hints as context about the shape of your data.
You can ask for them, too. A sample prompt: "Create a beginner Python example focused on list operations for a shopping scenario, and use type hints on variables." Then read what comes back. Hints on functions come later, in Type hints on functions.
All four together
prices: dict[str, float] = {
"milk": 1.50,
"eggs": 3.00,
"bread": 2.25,
}
cart: list[str] = ["milk", "eggs", "milk"]
unique: set[str] = set(cart)
dims: tuple[int, int] = (30, 20)
print(len(cart), "items,", len(unique), "different")
print("Price of milk:", prices["milk"])
print("Price list total:", sum(prices.values()))
print("Has cheese?", "cheese" in prices)
print("Box size:", dims[0], "x", dims[1])
3 items, 2 different
Price of milk: 1.5
Price list total: 6.75
Has cheese? False
Box size: 30 x 20
Prices are a dict because you look a price up by name. The cart is a list because order matters and repeats are fine (milk is there twice). unique is a set, so the repeat drops out. dims is a tuple because a box size is a fixed pair. Careful with the total: 6.75 is every price on the list once, not the cost of this cart.
Quick recap
| You need | Use | Write |
|---|---|---|
| order and changes | list | ["a", "b"] |
| fixed values | tuple | (3, 4), (7,) |
| no repeats | set | {1, 2}, empty: set() |
| look up by key | dict | {"k": v}, empty: {} |
| a label for readers and tools | type hint | scores: dict[str, int] |
Try it yourself
In the cart example, add a stock dictionary with the hint dict[str, int], and read one value with get. Or prompt an AI tool to write it, then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)