Python Sets
Python · Sets
Theory
A set is an unordered collection of unique items, written with curly braces: {'Mumbai', 'Delhi', 'Mumbai'} becomes {'Mumbai', 'Delhi'} because duplicates are dropped automatically. Internally a set is a hash table: Python computes hash(item) to decide where to store each item, so checking x in my_set or adding an item takes roughly constant time on average (O(1)), no matter how big the set is.
That design has consequences. Items must be hashable (immutable), so numbers, strings and tuples are fine, but lists and dicts raise TypeError. There is no index, so my_set[0] is an error, and the printed order is not guaranteed; string sets can even print in a different order between runs. {} creates an empty dict, not a set, so write set() for an empty set. Sets support maths-style operations: union |, intersection &, difference - and symmetric difference ^. frozenset is the immutable version.
Why we use it
Two very common questions are 'what are the distinct values?' and 'is this value in the collection?'. A set answers both efficiently: set(list) deduplicates in one call, and membership tests stay fast even with millions of items.
When to use it
Use a set to remove duplicates, for fast membership checks and to compare groups (common customers, new IDs). Use a list when order or duplicates matter, and dict.fromkeys(items) when you need unique items in their original order.
How it works
- Create a set from items, e.g. set(visits)
- Take the next item and compute hash(item)
- Is an equal item already in the set? Yes: Skip it (no duplicate). No: Store it in the hash table.
- Repeat until all items are processed
- Result contains each value once; order is not guaranteed
Syntax
my_set = {item1, item2}Example
unique_cities = {'Mumbai', 'Delhi', 'Mumbai'}
# {'Mumbai', 'Delhi'}Key points
- Automatically removes duplicates
- Membership tests (x in s) are average O(1)
- Unordered: no indexing, and print order is not guaranteed
- Items must be hashable: a list cannot be a set item
- {} is an empty dict; use set() for an empty set
- Support union, intersection and difference operations