What are Python Sets?
A set is an unordered collection of unique items. This mirrors mathematical sets — duplicates are automatically removed. Sets are highly optimized for testing if an item is present (membership tests) in O(1) time complexity.
python
Creating Sets
Warning! Python represents an empty dictionary as
{}. To create an empty set, you must use the set() constructor.python
Important Methods
| Method | Action | Example |
|---|---|---|
| .add(x) | Add x to the set | fruits.add("cherry") |
| .remove(x) | Remove x (raises ERROR if missing) | fruits.remove("apple") |
| .discard(x) | Remove x (safe, no error if missing) | fruits.discard("apple") |
| .pop() | Remove and return an arbitrary item | val = fruits.pop() |
| .clear() | Remove all items | fruits.clear() |
python
Powerful Set Operations (Math Mode!)
This is where sets truly shine. You can compute the relationship between two sets using Python's intuitive operators.
python
Advanced Set Logic: Subsets and Supersets
python
Frozensets: Immutable Sets
A standard set is mutable, which means it cannot be used as a key in a dictionary or as an item in another set. Frozenset is the immutable version!
python
Summary
| Feature | Method / Syntax |
|---|---|
| Uniqueness | Automatic duplicate removal |
| Add | .add(item) |
| Remove | .discard(item) (safe), .remove(item) (error) |
| Union | `A |
| Intersection | A & B |
| Difference | A - B |
| Symmetric Diff | A ^ B |
| Membership | x in set (high-performance!) |
| Best For | Membership tests, duplicate removal, math operations |