Python Cheatsheet

Sets

Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Creating Sets

s = set()                    # empty set (NOT {} — that's a dict!)
s = {1, 2, 3}
s = set([1, 2, 2, 3])       # {1, 2, 3}  — duplicates removed
s = set("hello")             # {'h', 'e', 'l', 'o'}
s = set(range(5))            # {0, 1, 2, 3, 4}

Set Methods (Mutating)

MethodDescriptionExample
add(x)Add elements.add(4)
remove(x)Remove x (KeyError if missing)s.remove(2)
discard(x)Remove x (no error if missing)s.discard(99)
pop()Remove and return arbitrary elements.pop()
clear()Remove all elementss.clear()
update(*others)Add all elements from others (in-place union)s.update([4, 5])
intersection_update(*others)Keep only elements in alls.intersection_update(t)
difference_update(*others)Remove elements found in otherss.difference_update(t)
symmetric_difference_update(other)Keep elements in exactly ones.symmetric_difference_update(t)

Set Operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union — elements in either
a | b                    # {1, 2, 3, 4, 5, 6}
a.union(b)
a.union(b, c, d)         # multiple sets

# Intersection — elements in both
a & b                    # {3, 4}
a.intersection(b)

# Difference — in a but not in b
a - b                    # {1, 2}
a.difference(b)

# Symmetric difference — in exactly one
a ^ b                    # {1, 2, 5, 6}
a.symmetric_difference(b)

# In-place versions
a |= b    # a.update(b)
a &= b    # a.intersection_update(b)
a -= b    # a.difference_update(b)
a ^= b    # a.symmetric_difference_update(b)

Set Predicates

a = {1, 2, 3}
b = {1, 2}
c = {4, 5}

# Subset / superset
b.issubset(a)         # True  — all of b in a
b <= a                # True
b < a                 # True  (proper subset: b != a too)
a.issuperset(b)       # True  — all of b in a
a >= b                # True
a > b                 # True  (proper superset)

# Disjoint — no elements in common
a.isdisjoint(c)       # True
a.isdisjoint(b)       # False

Membership and Length

s = {1, 2, 3}

1 in s          # True  — O(1) average
4 not in s      # True

len(s)          # 3
min(s)          # 1
max(s)          # 3
sum(s)          # 6

frozenset

Immutable version of set; hashable (can be used as dict key or set element).

fs = frozenset([1, 2, 3])
fs = frozenset({1, 2, 3})

# All read operations work
1 in fs
len(fs)
fs | {4}         # returns new frozenset
fs & {1, 2}      # frozenset({1, 2})
fs - {1}         # frozenset({2, 3})

# Mutating operations don't exist
# fs.add(4)  → AttributeError

# As dict key
d = {frozenset({1, 2}): "pair"}

# As set element
s = {frozenset({1, 2}), frozenset({3, 4})}

Iteration

s = {3, 1, 4, 1, 5, 9}

for x in s:            # order is arbitrary
    print(x)

sorted(s)              # sorted list: [1, 3, 4, 5, 9]
list(s)                # list (arbitrary order)

Set Comprehension

{x ** 2 for x in range(10)}            # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
{x for x in data if x > 0}
{word.lower() for word in text.split()}

Common Patterns

# Deduplicate a list (order not preserved)
unique = list(set(lst))

# Deduplicate preserving order
seen = set()
unique = [x for x in lst if not (x in seen or seen.add(x))]

# Find duplicates
from collections import Counter
dupes = {x for x, count in Counter(lst).items() if count > 1}

# Elements in list1 but not list2
diff = set(list1) - set(list2)

# Shared elements
common = set(list1) & set(list2)

# All unique elements across two lists
all_unique = set(list1) | set(list2)

# Power set
from itertools import combinations
def power_set(s):
    s = list(s)
    return [set(c) for r in range(len(s)+1) for c in combinations(s, r)]