Skip to content
  • Sets · Python

Sets

LearnViaNotes @learnvianotes· 1 min read

A set is an unordered collection of unique, hashable items with O(1) membership tests — and real set algebra.

Python
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b)          # {1, 2, 3, 4, 5}
print(a & b)          # {3, 4}
print(a - b)          # {1, 2}
print(a ^ b)          # {1, 2, 5}
print({1, 2} <= a)    # True
OperatorMethodMeaning
a | ba.union(b)In either
a & ba.intersection(b)In both
a - ba.difference(b)In a but not b
a ^ ba.symmetric_difference(b)In exactly one
a <= ba.issubset(b)Every item of a is in b

Adding & removing

Python
s = set()                  # {} would be an empty *dict*
s.add(3); s.add(3); s.add(1)
s.discard(99)              # no error if missing
print(sorted(s), len(s))   # [1, 3] 2

When to reach for a set

Python
xs = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(xs)))                   # [3, 1, 2]
def has_duplicate(nums):
    return len(set(nums)) != len(nums)
print(has_duplicate(xs), has_duplicate([1, 2]))  # True False

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report