← Back to Tutorials Chapter 7

Sets

Set Basics

A set is an unordered collection of unique, immutable elements enclosed in curly braces {}:

fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 2, 1}   # {1, 2, 3} — duplicates removed
empty_set = set()            # not {} — that's a dict!
mixed = {1, "hello", (1, 2)}  # must be hashable elements

Adding and Removing Elements

s = {1, 2, 3}

s.add(4)          # {1, 2, 3, 4}
s.update([5, 6])  # {1, 2, 3, 4, 5, 6}
s.add(1)          # no change (already exists)

s.remove(3)       # {1, 2, 4, 5, 6}
# s.remove(99)    # KeyError!
s.discard(99)     # no error (safe remove)
popped = s.pop()  # removes and returns arbitrary element
s.clear()         # set()

Set Operations

Sets support mathematical set operations:

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

a | b           # union: {1, 2, 3, 4, 5, 6}
a.union(b)      # same

a & b           # intersection: {3, 4}
a.intersection(b)  # same

a - b           # difference: {1, 2}
a.difference(b) # same

a ^ b           # symmetric difference: {1, 2, 5, 6}
a.symmetric_difference(b)  # same

Comparison Operators

{1, 2}.issubset({1, 2, 3})   # True
{1, 2} <= {1, 2, 3}         # True (subset)
{1, 2, 3}.issuperset({1, 2})  # True
{1, 2, 3} >= {1, 2}         # True (superset)
{1, 2}.isdisjoint({3, 4})   # True (no common elements)

Useful Set Methods

s = {3, 1, 4, 1, 5}
len(s)           # 4 (duplicates removed)
1 in s           # True
99 not in s      # True
copy = s.copy()  # shallow copy

Set Comprehension

squares = {x ** 2 for x in range(10)}
evens = {x for x in range(20) if x % 2 == 0}
print(squares)  # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

Frozenset

An immutable version of a set:

fs = frozenset([1, 2, 3, 2, 1])
# fs.add(4)  # AttributeError!
# fs.remove(1)  # AttributeError!

# Useful as dict keys or in other sets
sets_set = {frozenset([1, 2]), frozenset([3, 4])}

Common Use Cases

# Remove duplicates from a list
items = [1, 2, 3, 2, 1, 4, 3]
unique = list(set(items))  # [1, 2, 3, 4]

# Find common elements
friends_a = {"Alice", "Bob", "Charlie"}
friends_b = {"Bob", "Diana", "Eve"}
common = friends_a & friends_b  # {"Bob"}

# Check if all items in one list are in another
required = {"name", "email", "age"}
provided = {"name", "email"}
missing = required - provided  # {"age"}
Python set Venn diagram
Note: Sets are significantly faster than lists for membership tests (in / not in) because sets use hash tables internally. Use sets when order does not matter and uniqueness is required.

Practice Exercise

Create two lists of random numbers (10 numbers each, some overlapping). Convert them to sets and find: (1) all unique numbers across both lists, (2) numbers common to both, (3) numbers only in the first set, (4) numbers that appear in only one of the sets. Then write a function that takes two lists and returns the number of unique elements they share.