Python Sets
A set is an unordered collection of unique items. Sets remove duplicates automatically, answer “is this item here?” very fast, and support the union and intersection operations you know from maths.
- Create sets and remove duplicates
- Add and remove items safely
- Union, intersection and difference
- Subset checks and frozenset
Create a set
Write items inside curly braces, or call set() on any iterable. Duplicates are dropped.
tags = {"python", "testing", "python", "api"}print(len(tags))print(sorted(tags)) letters = set("mississippi")print(sorted(letters))3 ['api', 'python', 'testing'] ['i', 'm', 'p', 's']
{} creates an empty dictionary, not a set. Use set() for an empty set.
print(type({}).__name__, type(set()).__name__)dict set
Sets are unordered
A set has no positions, so there is no indexing or slicing. Loop over it, or convert it to a sorted list when you need an order.
colors = {"red", "green", "blue"}print(sorted(colors))print(colors[0])['blue', 'green', 'red']
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(colors[0])
~~~~~~^^^
TypeError: 'set' object is not subscriptableMembership is fast
Checking x in some_set takes about the same time however big the set is, while x in some_list has to look through the items one by one. For repeated lookups, convert to a set first.
blocked = {"spam.com", "bad.org", "phish.net"}for domain in ["good.in", "bad.org"]: print(domain, "blocked" if domain in blocked else "allowed")good.in allowed bad.org blocked
Add and remove items
skills = {"python", "sql"}skills.add("selenium")skills.update(["playwright", "python"]) # add severalprint(sorted(skills)) skills.remove("sql") # KeyError if missingskills.discard("java") # no error if missingprint(sorted(skills)) item = skills.pop() # removes an arbitrary itemprint(len(skills))['playwright', 'python', 'selenium', 'sql'] ['playwright', 'python', 'selenium'] 2
Set operations
| Operation | Operator | Method | Result |
|---|---|---|---|
| Union | a | b | a.union(b) | Items in either set |
| Intersection | a & b | a.intersection(b) | Items in both |
| Difference | a - b | a.difference(b) | Items in a but not b |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | Items in exactly one |
python_devs = {"asha", "ravi", "meena", "john"}java_devs = {"ravi", "john", "sara"} print(sorted(python_devs | java_devs))print(sorted(python_devs & java_devs))print(sorted(python_devs - java_devs))print(sorted(python_devs ^ java_devs))['asha', 'john', 'meena', 'ravi', 'sara'] ['john', 'ravi'] ['asha', 'meena'] ['asha', 'meena', 'sara']
Subsets and supersets
required = {"python", "sql"}candidate = {"python", "sql", "git"} print(required <= candidate) # issubsetprint(candidate >= required) # issupersetprint(required.isdisjoint({"java"})) # no items in commonTrue True True
Remove duplicates from a list
emails = ["a@x.com", "b@x.com", "a@x.com"]print(len(set(emails))) # count of unique itemsprint(sorted(set(emails)))print(list(dict.fromkeys(emails))) # unique AND original order2 ['a@x.com', 'b@x.com'] ['a@x.com', 'b@x.com']
frozenset
A frozenset is an immutable set. Because it cannot change, it can be a dictionary key or an item of another set.
team_a = frozenset({"asha", "ravi"})history = {team_a: "won final"}print(history[frozenset({"ravi", "asha"})])won final
Check your understanding
Predict the output
a = {1, 2, 3, 4}b = {3, 4, 5}print(sorted(a - b), sorted(b - a), len(a | b), a & b == {3, 4})[1, 2] [5] 5 True
Difference is not symmetric: a - b keeps 1 and 2, b - a keeps only 5. The union has five unique items.
Quick quiz
1. What does {} create?
Use set() for an empty set.
2. Which method does NOT raise an error when the item is missing?
discard() silently does nothing; remove() raises KeyError.
3. What is {1, 2} & {2, 3}?
& is intersection: items in both sets.
Exercise: common and unique skills
Two candidates list their skills. Print the skills they share, the skills only the first has, and how many different skills they have together.
c1 = ["python", "sql", "git", "docker"], c2 = ["java", "sql", "git"]
Shared: ['git', 'sql'] Only first: ['docker', 'python'] Total different: 5
Hint 1
Convert both lists to sets first.
c1 = set(["python", "sql", "git", "docker"])c2 = set(["java", "sql", "git"]) print("Shared:", sorted(c1 & c2))print("Only first:", sorted(c1 - c2))print("Total different:", len(c1 | c2))Shared: ['git', 'sql'] Only first: ['docker', 'python'] Total different: 5
Each question maps to one set operation: intersection, difference and union. sorted() gives a stable order for printing.
Program Practice
48 Python Set Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python sets FAQ
Is a Python set ordered?
No. Sets do not keep insertion order and cannot be indexed. Use sorted(s) to get an ordered list.
How do I create an empty set in Python?
Use set(). {} creates an empty dictionary.
What is the difference between remove() and discard()?
Both remove an item. remove() raises KeyError if the item is missing; discard() does nothing.
Can a set contain a list?
No. Set items must be hashable. Use a tuple instead of a list.