Set Theory Operations
Sets support standard mathematical set operations.
Let A = {1, 2, 3} and B = {3, 4, 5}.
1. Union (Combining Sets)
Returns a new set containing all elements from both sets. Use the | operator or the .union() method.
python A = {1, 2, 3} B = {3, 4, 5} union_set = A | B print(union_set) # {1, 2, 3, 4, 5}
2. Intersection (Common Elements)
Returns a new set containing only the elements common to both sets. Use the & operator or the .intersection() method.
python intersection_set = A & B print(intersection_set) # {3}
3. Difference (Elements in A but not B)
Returns a set containing elements present in the first set but not in the second. Use the - operator or the .difference() method.
python difference_set = A - B print(difference_set) # {1, 2}
4. Subset and Superset
A.issubset(B): True if every element in A is in B.A.issuperset(B): True if every element in B is in A.
python C = {1, 2} print(C.issubset(A)) # True