A set is an unordered collection of unique items: tags = {"python", "web"}.
Create
{1, 2, 3}set([1, 1, 2])→{1, 2}— duplicates removed- Empty set:
set()—{}creates an empty dictionary
Add and remove
add(x), update([...]), remove(x) (error if missing), discard(x) (no error), pop(), clear().
Set operations
| Operation | Operator | Meaning |
|---|---|---|
| Union | a | b |
in either |
| Intersection | a & b |
in both |
| Difference | a - b |
in a, not b |
| Symmetric difference | a ^ b |
in one, not both |
Also issubset(), issuperset(), isdisjoint().
Why sets?
- Remove duplicates quickly
- Very fast
inchecks, even with millions of items - Compare groups (common friends, missing items)
Sets have no index — you cannot do s[0]. Items must be immutable (numbers, strings, tuples).
Example
Example — Course enrolments
Python
python_batch = {"Asha", "Ravi", "Neha", "Amit"}
web_batch = {"Ravi", "Zoya", "Amit"}
print("Both courses:", python_batch & web_batch)
print("Any course:", python_batch | web_batch)
print("Only Python:", python_batch - web_batch)
print("Exactly one:", python_batch ^ web_batch)
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
unique = set(emails)
print(len(emails), "->", len(unique))
blocked = {"spam@x.com"}
print("spam@x.com" in blocked)
print(type({}), type(set()))
Shows students in both courses {'Ravi', 'Amit'}, the union, Python-only students, and those in exactly one course (set order may vary). Then 5 -> 3, True, and <class 'dict'> <class 'set'>.