compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
list vs tuplebehaves differently
Store a point and try to change it, use it as a dict key, and add to it.
what differs
Lists are mutable and unhashable. Tuples are immutable, so they can be dict keys and set members; ‘changing’ one makes a new tuple.
at a glance
| approach | use it when |
|---|---|
| A · list | A variable-length sequence of similar items that changes. |
| B · tuple | A fixed-size record whose positions mean different things, or a key. |
Watch out: A tuple containing a list is still not hashable, and the list inside can change. (1) is just 1; a one-item tuple is (1,).
the outputs
Each approach runs on the same input.
concepts
mutabilityhashability
learn it
related comparisons
Mutable records vs immutable records · NamedTuple vs frozen dataclass