Choosing the right structure
Match the container to the access pattern. Lists for ordered, mutable sequences. Tuples for immutable records. Sets for membership and uniqueness. Dicts for labelled lookup. Using the wrong one costs performance: e.g. 'x' in list is O(n) while 'x' in set is O(1) average.
Complexity at a glance
| Operation | list | dict | set |
|---|---|---|---|
| Index/lookup | O(n) | O(1)* | O(1)* |
| Append | O(1)* | , | , |
| Membership | O(n) | O(1)* | O(1)* |
* is amortised average case. Prefer dict/set for frequent membership checks.