Python Set Methods
In this page:
Adding and Removing Elements
add() inserts one element at a time; when removing, prefer discard() over remove() unless you specifically want an exception raised for a missing element -- discard() lets you write cleanup code without wrapping every call in try/except.
Example: Adding and Removing Elements
s = {1, 2, 3}
s.add(4)
s.discard(10)
print(s)
Set Union
union() merges two sets into a new one with duplicates removed automatically; the | operator does the exact same thing with less typing, and both work with any number of sets chained together (a | b | c).
Example: Set Union
a = {1, 2}
b = {2, 3}
print(a.union(b))
print(a | b)
Set Intersection
intersection() returns only the elements common to both sets, and & is its operator shorthand -- a typical use is finding which tags two articles share, or which users are in two different groups.
Example: Set Intersection
a = {1, 2, 3}
b = {2, 3, 4}
print(a.intersection(b))
print(a & b)
Set Difference
difference() returns what's in the first set but not the second (- is the shorthand), while symmetric_difference() returns elements unique to either set alone -- the two are easy to confuse, so it helps to think of symmetric_difference as 'the XOR of two sets'.
Example: Set Difference
a = {1, 2, 3}
b = {2, 3}
print(a.difference(b))
print(a.symmetric_difference(b))
Checking Set Relationships
issubset() checks whether all of a set's elements exist in another set, issuperset() checks the reverse relationship, and isdisjoint() confirms two sets share zero elements in common -- useful for quickly detecting conflicting or overlapping selections.
Example: Checking Set Relationships
a = {1, 2}
b = {1, 2, 3}
c = {5, 6}
print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint(c))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: