set.union()
Python · Sets
Theory
.union(other) returns a new set containing every item that is in either set, with each value appearing only once. With a = {1, 2, 3} and b = {2, 3, 4}, a.union(b) is {1, 2, 3, 4}. Neither a nor b is changed. The operator form a | b does the same thing, and you can combine several sets at once: a.union(b, c) or a | b | c.
There is a small difference between the two forms: the method accepts any iterable, so a.union([4, 5]) works with a list, while the | operator requires both sides to be sets. To modify a set in place instead of creating a new one, use a.update(b) or a |= b. Union costs about O(len(a) + len(b)) because every item from both sides is hashed once. A practical example is merging customer IDs from two campaigns to get everyone reached at least once.
Why we use it
Combining groups without double counting is a common need: all products sold in either city, every user active this week or last week. union() merges them and removes overlap automatically.
When to use it
Use union() or | to combine groups of unique values. Use update() or |= when you want to grow an existing set in place. If you need to keep duplicates or order, concatenate lists instead.
How it works
- Call a.union(b)
- Start a new set with a copy of a
- Take the next item from b
- Is it already in the new set? Yes: Skip it. No: Add it.
- Return {1, 2, 3, 4}; a and b are unchanged
Syntax
set1.union(set2)Example
a = {1,2,3}
b = {2,3,4}
print(a.union(b))Key points
- Equivalent to the | operator: a | b
- Duplicates across the two sets appear only once in the result
- Returns a new set; the originals are unchanged
- The method accepts any iterable; | needs both sides to be sets
- update() or |= merges into the existing set in place