Sets
What it means
Section titled βWhat it meansβA set ({1, 2, 3}) is an unordered collection of unique, hashable items β duplicates are automatically discarded. Sets are optimized for fast membership testing (in) and for mathematical set operations like union, intersection, and difference.
Examples
Section titled βExamplesβfruits = {"apple", "banana", "apple"} # {'apple', 'banana'} -- duplicate dropped
fruits.add("cherry")fruits.discard("banana") # remove if present, no error if missing
a = {1, 2, 3}b = {2, 3, 4}
print(a | b) # union: {1, 2, 3, 4}print(a & b) # intersection: {2, 3}print(a - b) # difference: {1}print(a ^ b) # symmetric difference: {1, 4}
# Fast membership testprint(3 in a) # True -- O(1) average, unlike checking a listCommon mistake
Section titled βCommon mistakeβTrying to create an empty set with {} β that actually creates an empty dict, not a set, because {} is the dict literal.
empty = {}print(type(empty)) # <class 'dict'> <- not a set!
empty_set = set()print(type(empty_set)) # <class 'set'> <- correct wayQuick practice
Section titled βQuick practiceβ-
What happens when you add a duplicate item to a set?
Answer
Nothing changes β sets silently ignore additions of items that already exist. -
How do you create an empty set?
Answer
set()β not{}, which creates an empty dict instead. -
Why is checking
x in my_setgenerally faster thanx in my_list?Answer
Sets use a hash table internally, giving average O(1) membership checks, while lists require a linear O(n) scan.