Beginner Chapter 51 · 25 min read · Module 4: Python Data Structures
Set Operations
- After this chapter you can combine two sets with union and find shared items with intersection.
- You can find items that are only in one set using difference and symmetric difference.
- You can test relationships with issubset, issuperset and isdisjoint.
- You can choose between operators and methods and use the in-place update forms safely.
Sets are great at one job: answering questions about groups of items. Which students joined both clubs? Which products are in stock but not yet ordered? Which tags appear in only one of two posts? These questions come from school maths, where they are called set operations, and Python supports them directly.
Every operation in this chapter has two forms. The operator form, such as a | b, is short and easy to read. The method form, such as a.union(b), is longer but accepts any iterable, like a list or a tuple. Both give the same answer when both sides are sets.
Because a set never keeps duplicates and has no fixed order, the results are also sets. In the examples we sort the results before printing, so the output is always the same on every machine.
Union: everything from both sets
The union of two sets contains every item that appears in at least one of them. Items that appear in both are kept only once, because a set cannot hold duplicates. Use the | operator or the union() method.
a = {1, 2, 3}
b = {3, 4, 5}
print(sorted(a | b))
print(sorted(a.union(b)))
print(sorted(a.union([9, 10], (11,))))Notice the last line. The method union() accepts a list and a tuple, and even several arguments at once. The operator | would raise a TypeError if one side was a list.
Intersection: only what is shared
The intersection contains only the items that appear in both sets. Use & or intersection(). If the two sets share nothing, the result is an empty set.
python_club = {"Asha", "Ravi", "Mina"}
chess_club = {"Ravi", "Tara", "Mina"}
both = python_club & chess_club
print(sorted(both))
print(python_club.intersection({"Zed"}))set(), not {}. Curly braces with nothing inside create an empty dictionary.Difference: in one set but not the other
The difference a - b keeps the items of a that are not in b. Order matters here: a - b and b - a are usually different. Use - or difference().
Symmetric difference: in exactly one set
The symmetric difference contains items that are in one set or the other, but not in both. Use ^ or symmetric_difference(). You can think of it as the union with the intersection removed.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(sorted(a - b))
print(sorted(b - a))
print(sorted(a ^ b))
print(sorted((a | b) - (a & b)))| Operation | Operator | Method | Meaning |
|---|---|---|---|
| Union | a | b | a.union(b) | in a or b or both |
| Intersection | a & b | a.intersection(b) | in both |
| Difference | a - b | a.difference(b) | in a only |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | in exactly one |
Comparing sets
Sometimes you do not need a new set, only a yes or no answer. a <= b or a.issubset(b) is True when every item of a is also in b. a >= b or a.issuperset(b) is the reverse. a.isdisjoint(b) is True when the sets have nothing in common. The operators < and > mean a strict subset or superset, so a set is never a strict subset of itself.
small = {1, 2}
big = {1, 2, 3}
print(small <= big)
print(small < small)
print(big.issuperset(small))
print(small.isdisjoint({7, 8}))
print(small.isdisjoint(big))In-place updates
Each operation has an update form that changes the left set instead of making a new one: |= or update(), &= or intersection_update(), -= or difference_update(), and ^= or symmetric_difference_update(). These return None, so never write a = a.update(b). That would replace your set with None.
stock = {"pen", "book", "ruler"}
sold = {"book"}
stock -= sold
print(sorted(stock))
stock |= {"bag", "pen"}
print(sorted(stock))
result = stock.update({"cap"})
print(result)Operators versus methods
Use operators when both sides are already sets, because the code reads like maths. Use methods when one side may be a list, a string, or another iterable, so you do not have to convert it first. Remember that a string is an iterable of characters: set().union("hello") gives the letters, not the word.
Choosing the right operation
When a problem mentions two groups, ask yourself which question you are really answering. If you want everybody from both groups, use union. If you want only the people or items that appear in both, use intersection. If you want what one group has that the other lacks, use difference, and remember that the order of the two sets matters here. If you want the items that do not match between two groups, use symmetric difference. Putting the question into plain words first makes the correct operator easy to pick, and it keeps your code short and readable.
A good habit is to name your sets after what they hold, such as enrolled_math and enrolled_art, and then write one line per question. For example, students who take both subjects are enrolled_math & enrolled_art, and students who take math but not art are enrolled_math - enrolled_art. Because each result is a new set, you can chain steps together, store the answers in variables, and print them in a sorted order so that the output is always stable and easy to test.
Remember that sets keep only unique items and have no fixed order. If you need a predictable display, wrap the result in sorted() before printing. This is also why the chapter examples print sorted lists instead of raw sets. Items inside a set must be hashable, so numbers, strings and tuples work, but lists and dictionaries do not. Finally, operations on very large sets are quick because Python checks membership by hashing, which is one more reason to prefer sets over lists for comparing collections.
Set operations are fast. Python does not scan the full list for every item; it uses hashing, so finding common items between two large collections is much quicker with sets than with nested loops over lists. This is why removing duplicates and comparing groups are classic uses for sets.
Python syntax
a | b # union
a & b # intersection
a - b # difference
a ^ b # symmetric differencea.union(b, c)
a.intersection(b)
a.difference(b)
a.symmetric_difference(b)a <= b a.issubset(b)
a >= b a.issuperset(b)
a.isdisjoint(b)Real-world applications
- Finding customers who bought in both months (intersection).
- Finding new users who are in today's list but not yesterday's (difference).
- Merging tag lists from several posts without duplicates (union).
- Checking that a user has all required permissions (issubset).
Common mistakes
{} to make an empty set.Fix: Use
set(). Empty curly braces make a dictionary.update() such as a = a.update(b).Fix:
update() changes the set in place and returns None. Just call a.update(b).a | [1, 2] with a list on one side.Fix: Operators need two sets. Use
a.union([1, 2]) or convert the list with set().a - b equals b - a.Fix: Difference is not symmetric. Choose the order carefully, or use
^ for items in only one set.Important tips
- Sort a set with
sorted()before printing so the output is stable. - Use
isdisjoint()when you only need a yes or no answer; it can stop early. - Read
a & bas 'a and b',a | bas 'a or b'.
Key points summary
- Union, intersection, difference and symmetric difference all return new sets.
- Operators need sets; methods accept any iterable.
- Update forms change the set in place and return None.
- Subset and superset tests return True or False.
- Difference depends on order; the others (except difference) do not.
Exam and interview points
|,&,-,^map to union, intersection, difference, symmetric difference.{}is a dict;set()is the empty set.a <= ballows equality;a < bdoes not.- Update methods return None.
Quick revision
- Union: all items, once each.
- Intersection: shared items.
- Difference: left only.
- Symmetric difference: not shared.
- Methods accept any iterable; operators need sets.
Frequently asked questions
What is the difference between `a - b` and `a ^ b`?
`a - b` keeps items only in `a`. `a ^ b` keeps items that are in exactly one of the two sets, so it includes items only in `b` as well.
Can I use these operations on lists?
Not directly. Convert lists to sets first with `set()`. The method forms accept a list as the argument, but the left side must still be a set.
Do set operations keep the original order?
No. Sets have no guaranteed order, so sort the result if you need a predictable display.
Is an empty set a subset of every set?
Yes. `set() <= anything` is True because there are no items that could be missing.
Practise this chapter
21 practice questions Take the chapter quiz