Unordered collections of unique items, with fast membership tests and set algebra.
# create a set
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
empty = set()
# ans: not {}, which is an empty dict!
A set keeps one copy of each value: set([1, 2, 2, 3]) is {1, 2, 3}.
# add a single item
fruits = {"apple", "banana"}
fruits.add("cherry")
# ans: {"apple", "banana", "cherry"}
# remove (raises an error if not found)
fruits = {"apple", "banana"}
fruits.remove("apple")
# ans: {"banana"}
# discard (no error if not found)
fruits.discard("cherry")
# ans: {"banana"}
# union (combines all)
a = {1, 2, 3}
b = {3, 4, 5}
a | b
# ans: {1, 2, 3, 4, 5}
a.union(b)
# ans: {1, 2, 3, 4, 5}
# intersection (common elements)
a = {1, 2, 3}
b = {2, 3, 4}
a & b
# ans: {2, 3}
a.intersection(b)
# ans: {2, 3}
# difference (in a but not b)
a = {1, 2, 3}
b = {2, 3, 4}
a - b
# ans: {1}
a.difference(b)
# ans: {1}
# symmetric diff (in either but not both)
a = {1, 2, 3}
b = {2, 3, 4}
a ^ b
# ans: {1, 4}
a.symmetric_difference(b)
# ans: {1, 4}
Predict each result, then press → to check.
# duplicates in a set?
s = {1, 2, 2, 3}
# ans: {1, 2, 3}
# empty set?
s = {}
type(s)
# ans: <class 'dict'>
s = set()
type(s)
# ans: <class 'set'>
# add an existing element?
s = {1, 2}
s.add(2)
# ans: {1, 2} (no change)
# remove something that isn't there?
s = {1, 2}
s.remove(3)
# ans: KeyError
s.discard(3)
# ans: no error
# union result?
a = {1, 2}
b = {2, 3}
a | b
# ans: {1, 2, 3}
# empty intersection?
a = {1, 2}
b = {3, 4}
a & b
# ans: set()
An empty set prints as set(), because {} means an empty dict.
# subset check?
a = {1, 2}
b = {1, 2, 3}
a.issubset(b)
# ans: True
# set from a list?
lst = [1, 2, 2, 3]
s = set(lst)
# ans: {1, 2, 3}
# set membership?
s = {1, 2, 3}
2 in s
# ans: True
Membership tests are what sets are fastest at, even for millions of items.
# pop from a set?
s = {1, 2, 3}
s.pop()
# ans: an arbitrary element (don't rely on which)
Sets have no order, so there is no "last" item to pop.
Duplicates collapse; there are no indexes.
set(), not {}Empty braces make a dict.
remove raises KeyError if missing; discard doesn't.
| & - ^Union, intersection, difference, symmetric difference.