×
Sets
{} → empty dictionary, not set.
set() → empty set.
{1,} → a set with one element (the comma is optional but allowed for single-element sets).
1. Union (| or .union())
A = {1, 2, 3}
B = {3, 4, 5}
A | B # {1, 2, 3, 4, 5}
A.union(B) # {1, 2, 3, 4, 5}
2. Intersection (& or .intersection())
A = {1, 2, 3}
B = {3, 4, 5}
A & B # {3}
A.intersection(B) # {3}
3. Difference (- or .difference())
A = {1, 2, 3}
B = {3, 4, 5}
A - B # {1, 2}
B - A # {4, 5}
A.difference(B) # {1, 2}
4. Symmetric Difference (^ or .symmetric_difference())
A = {1, 2, 3}
B = {3, 4, 5}
A ^ B # {1, 2, 4, 5}
A.symmetric_difference(B) # {1, 2, 4, 5}
5. Subset (<=, <) & Superset (>=, >)
A = {1, 2}
B = {1, 2, 3}
A <= B # True (A is a subset of B)
B >= A # True (B is a superset of A)
print(A < B) # True
print(B > A) # True
A.issubset(B) # True
B.issuperset(A) # True
>> Methods
s = {1, 2, 3}
The add() method only takes a single element at a time. If you try to pass a list or another iterable, it will treat the whole thing as one element
s.add(4) # {1,2,3,4}
s.add([5, 6]) # adds the *list itself* as one element
print(s) # {1, 2, 3, 4, [5, 6]} <-- note the list inside
The update() method lets you add multiple elements to a set at once, and you can pass it any iterable — like a list, tuple, or even another set. It adds all the elements that aren’t already in the set.
s.update([3,5]) # {1,2,3,4,5}
If you use remove(x) on a set and x is not in the set, Python will raise a KeyError.
s.remove(2) # {1,3,4,5}
If you want to avoid an error when the element might not exist, use discard(x) instead:
s.discard(10) # {1,3,4,5} (no error)
set.pop() does not remove the “last” element because sets in Python are unordered. It removes and returns an arbitrary element—which element you get is unpredictable.
elem = s.pop() # removes and returns an arbitrary element
clear() removes all elements from the set, leaving it empty. It doesn’t return anything.
s.clear() # s becomes set()