What is the difference between a list, a tuple, a set and a dictionary in Python?
Four built-in collections with different guarantees.
- list — ordered, mutable, allows duplicates. Indexing is O(1); membership testing with
inis O(n) because it scans. - tuple — ordered, immutable, allows duplicates. Because it is immutable it is hashable, so a tuple can be a dictionary key or a set member. Slightly smaller and faster than a list.
- set — unordered, mutable, no duplicates. Backed by a hash table, so membership testing is O(1). This is the reason to use one.
- dict — key-value pairs, mutable, keys unique and hashable. O(1) lookup. Insertion order has been guaranteed since Python 3.7.
How to choose: a list for an ordered sequence you will modify; a tuple for a fixed record or a return value of several items; a set when you need uniqueness or fast membership tests; a dict when you need to look something up by key.
Note: The performance point is the one that matters in practice. Replacing `if x in my_list` with a set inside a loop turns an O(n²) algorithm into O(n), and that single change fixes a surprising number of slow scripts.





