Python Sets
In this page:
What is a Set?
A set stores unique, unordered elements -- adding a duplicate silently does nothing -- and because sets use hashing internally, membership checks are much faster than scanning a list. Curly braces {} define a set, but an empty {} actually creates a dict, so use set() for an empty one.
Example: What is a Set?
numbers = {1, 2, 2, 3}
print(numbers)
empty = set()
print(type(empty))
Adding and Removing Items
add(item) inserts a single new element (no effect if it's already present), remove(item) deletes it but raises KeyError if missing, and discard(item) does the same removal without raising an error -- discard() is the safer choice when you're not sure the item is there.
Example: Adding and Removing Items
s = {1, 2, 3}
s.add(4)
s.discard(10)
print(s)
Union and Intersection
union() (or the | operator) returns a new set containing every element from both sets with duplicates automatically collapsed, which is the set-theory equivalent of combining two guest lists into one without repeats.
Example: Union and Intersection
a = {1, 2, 3}
b = {2, 3, 4}
print(a.union(b))
print(a.intersection(b))
Set Difference
difference() (or -) returns elements in the first set that aren't in the second, useful for finding whats in A but missing from B'; symmetric_difference() (or ^) returns elements that are in exactly one of the two sets, not both.
Example: Set Difference
a = {1, 2, 3}
b = {2, 3, 4}
print(a.difference(b))
print(a.symmetric_difference(b))
Set Membership and Checking
in checks membership just like it does for lists, but on a set it runs in roughly constant time regardless of size; issubset() checks whether every element of one set also appears in another, which is handy for permission or capability checks.
Example: Set Membership and Checking
a = {1, 2}
b = {1, 2, 3}
print(1 in b)
print(a.issubset(b))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: