Python Set Methods
In this page:
set_name.add(item)
set_name.remove(item)
set_a.union(set_b)
set_a.intersection(set_b)
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) # adds one element
s.discard(10) # safe removal, no error for a missing element
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)) # merges both sets, dropping duplicates
print(a | b) # same result using the operator shorthand
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)) # elements common to both
print(a & b) # same result using the operator shorthand
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)) # elements only in a
print(a.symmetric_difference(b)) # elements in exactly one of the two
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)) # every element of a is in b
print(b.issuperset(a)) # the reverse relationship
print(a.isdisjoint(c)) # True, a and c share no elements
- Using
remove()on a missing element, which raisesKeyError, whendiscard()does nothing if the element is absent. - Expecting
a.union(b)to changea, when it returns a new set; usea.update(b)to modify in place. - Confusing
pop()with listpop(), since a set'spop()removes an arbitrary element, not the last one added.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: