Python list, tuple, dict and set #1.2
Python has four types that hold several items: list, dict and set can change, a tuple cannot. Each fits a different job.
list, tuple, dict, set
What does the code below print?
tags = ["python", "redis"]
tags.append("go")
print(tags[-1], len(tags))
# prints: go 3
prices = {"redis": 199_000}
prices["python"] = 249_000
print(prices.get("go"), "python" in prices)
# prints: None True
seen = set(["a", "b", "a"])
print(len(seen))
# prints: 2
len(x)returns the number of items in a list, dict, set or string.prices.get("go")returnsNonebecause there is no key"go";prices["go"]raisesKeyError.
The whole lesson is about four types that hold several items: list, dict and set can change, a tuple cannot.
| list | tuple | dict | set | |
|---|---|---|---|---|
| Create | [1, 2] | (1, 2) | {"a": 1} | {1, 2} |
| Read | a[0], a[-1] | t[0] | d["a"], d.get("a") | no access by position |
| Add | a.append(3) | cannot | d["b"] = 2 | s.add(3) |
| Remove | a.pop(), a.remove(x) | cannot | del d["a"], d.pop("a") | s.discard(3) |
x in ... | slow, O(n) | slow, O(n) | fast, O(1), checks keys | fast, O(1) |
| Use for | a changing list of items | a fixed record, returning several values | lookup by key | removing duplicates, membership |
d["x"]with no key"x"raisesKeyError.d.get("x")returnsNoneinstead.- A
dictkeeps insertion order (since Python 3.7). - Adding or removing at the front of a list (
insert(0, x),pop(0)) is O(n). For both ends usedeque. - Checking membership many times on a list → switch to a set.
tuple: a fixed sequence
A tuple is an immutable sequence: once created, you cannot add, remove or reassign items. JS and Go have no such type, and the closest thing in Java is a record. Python uses tuples in many places where other languages use an array or a struct.
| Write | Meaning | Result |
|---|---|---|
point = (3, 4) | a two-item tuple | (3, 4) |
point = 3, 4 | the comma makes the tuple; brackets only help reading | (3, 4) |
(1,) | a one-item tuple needs the comma | (1,) |
x, y = point | unpacking: split the tuple into names | x = 3, y = 4 |
return low, high | a function returning several values returns one tuple | (1, 9) |
a, b = b, a | swap two variables | no temporary variable |
point = 3, 4
print(point)
# prints: (3, 4)
print(type((1)), type((1,)))
# prints: <class 'int'> <class 'tuple'>
x, y = point
print(x + y)
# prints: 7
point[0] = 10
# error: TypeError: 'tuple' object does not support item assignment
Returning several values and swapping two variables:
def min_max(nums):
return min(nums), max(nums)
result = min_max([4, 1, 9])
print(result)
# prints: (1, 9)
low, high = min_max([4, 1, 9])
print(low, high)
# prints: 1 9
a, b = 1, 2
a, b = b, a
print(a, b)
# prints: 2 1
A tuple can be a dict key, a list cannot (see hashability in #1.4):
distance = {(0, 0): "origin", (3, 4): "5 from the origin"}
print(distance[(3, 4)])
# prints: 5 from the origin
print({[3, 4]: "error"})
# error: TypeError: unhashable type: 'list'
Trap: a tuple holding a list.
order = ("Orbit", [101, 102])
order[1].append(103)
print(order)
# prints: ('Orbit', [101, 102, 103])
print(hash(order))
# error: TypeError: unhashable type: 'list'
order[1] is still the same list; only its contents changed. Because one item is mutable, hash(order) fails.
Named tuples: NamedTuple. When each position has its own meaning, give it a name so you can read p.x instead of p[0]:
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(3, 4)
print(p.x, p[1])
# prints: 3 4
print(p)
# prints: Point(x=3, y=4)
class Point(NamedTuple):creates a tuple type with field names;x: intdeclares a field's name and type. Classes are covered in #3.1.Pointis still a tuple: you can read it by position, and you cannot reassign it.
| Pick | When |
|---|---|
tuple | the number of items and the meaning of each position are fixed: coordinates, a key–value pair, several return values |
list | a changing list of items of the same kind |
NamedTuple | a tuple where each position deserves a name |
Key takeaways
- For repeated lookups use a dict or set (O(1)), not a list (O(n)).
- A tuple is immutable, made by the comma,
(1,)for one item; use it for fixed records, several return values and dict keys.
Sources
- Built-in Types (opens in a new tab): numbers, strings, list, dict, set, truth values.
- Every example with a
# printsline was run on Python 3.11.9.
