1What is the difference between a list, a tuple, a set and a dictionary?
| list | tuple | set | dict | |
|---|---|---|---|---|
| Syntax | [1, 2] | (1, 2) | {1, 2} | {"a": 1} |
| Ordered | yes | yes | no | yes (insertion order, 3.7+) |
| Mutable | yes | no | yes | yes |
| Duplicates | allowed | allowed | no | unique keys |
Lookup x in | O(n) | O(n) | O(1) average | O(1) average by key |
Use a list for an ordered collection that changes, a tuple for fixed records (coordinates, function returns) and as dictionary keys (they're hashable), a set for uniqueness and fast membership tests, and a dict for key-value lookups.