Python Sets
In this page:
set_name = {item1, item2, item3}
set_name = set(iterable)
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} # duplicate 2 is silently dropped
print(numbers)
empty = set() # {} alone would create a dict, not a 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) # inserts a new element
s.discard(10) # no error even though 10 isn't in the set
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)) # every element from both sets, no duplicates
print(a.intersection(b)) # only elements present in both
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)) # in a but not in b
print(a.symmetric_difference(b)) # in exactly one of the two sets
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) # membership check, fast on a set
print(a.issubset(b)) # True since every element of a is also in b
- Creating an empty set with
{}, which makes an empty dictionary; useset()instead. - Expecting a set to keep order or support indexing, as in
s[0], which raisesTypeErrorbecause sets are unordered. - Adding an unhashable item such as a list with
s.add([1, 2]), which raisesTypeError; use a tuple instead.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: