Advanced Python Set Methods
Python Advanced Set Methods
What is a Set?
A set is an unordered collection of unique elements in Python.
Example:
my_set = {1, 2, 3, 4}
Advanced Set Methods:
1. union() or |
Combine two sets (all unique elements).
Example: a.union(b) or a | b
2. intersection() or &
Common elements in both sets.
Example: a.intersection(b) or a & b
3. difference() or -
Elements in A but not in B.
Example: a.difference(b) or a - b
4. symmetric_difference() or ^
Elements in A or B, but not both.
Example: a.symmetric_difference(b) or a ^ b
5. issubset()
Check if all elements of A are in B.
Example: a.issubset(b)
Advanced Python Set Methods
6. issuperset()
Check if A contains all elements of B.
Example: a.issuperset(b)
7. isdisjoint()
Check if A and B have no elements in common.
Example: a.isdisjoint(b)
8. update()
Add elements from another set into the current set.
Example: a.update(b)
9. intersection_update()
Keep only the elements found in both sets.
Example: a.intersection_update(b)
10. difference_update()
Remove all elements in the current set that are also in another set.
Example: a.difference_update(b)
11. symmetric_difference_update()
Keep only elements that are unique to each set.
Example: a.symmetric_difference_update(b)
12. copy()
Create a shallow copy of a set.
Example: b = a.copy()
13. clear()
Remove all elements from the set.
Example: a.clear()
Advanced Python Set Methods
Set Comprehension:
You can build sets using expressions.
Example: squares = {x ** 2 for x in range(5)}
Summary Table:
Method | Description
------------------------------|------------------------------------------
union() / | | All unique elements from both sets
intersection() / & | Common elements
difference() / - | Elements only in the first set
symmetric_difference() / ^ | Elements in one set or the other, not both
issubset() | Check if set A is within B
issuperset() | Check if A contains all elements of B
isdisjoint() | Check if sets have no common elements
update() | Add elements from another set
clear() | Empty the set