Learning Python with Advent of Code Walkthroughs

Dazbo's Advent of Code solutions, written in Python

The Python Journey - Sets


Useful Links

Python Setsclasses

Sets are really useful when we want to store a number of unique items, but we don’t care about the order of those items.

Python sets have these attributes:

You should consider using sets whenever you need to:

Quick Demo

from dataclasses import dataclass

class Point():
    """ Point class, which stores x and y """
    x: int
    y: int
point_a = (5, 10)
point_b = (6, 5)
point_c = (5, 10)   # this is a duplicate (non-unique) point
point_d = (20, 30)

points = set()

print(f"Points contains {len(points)} points.")   # We've only added 2 unique points

print(f"Point c is in points? {point_c in points}")  # Because c and a are actually the same
print(f"Point d is in points? {point_d in points}")  # We haven't added this

# We can make a points list like this...
points_list = [point_a, point_b, point_c, point_d]  # 4 items
print(f"Points_list contains {len(points_list)} points.")   # still four items
print(f"Points_list: {points_list}")

# And now we can convert it to a set
# This is a convenient way to strip out duplicates from any collection!
points_set = set(points_list)
print(f"Points_set contains {len(points_set)} points.")   # now 3 items
print(f"Points_set: {points_set}")


Points contains 2 points.
Point c is in points? True
Point d is in points? False
Points_list contains 4 points.
Points_list: [(5, 10), (6, 5), (5, 10), (20, 30)]
Points_set contains 3 points.
Points_set: {(5, 10), (20, 30), (6, 5)}

Set Algebra

Mathematical set algebra is easily achieved using Python sets. For example, we can use set algebra to determine when one set contains another set, any intersection of sets, any difference between sets, and any union that is created by combining sets. If you’re unfamiliar with set theory, but you understand Venn diagrams, then guess what… You pretty much understand set theory!

Set Relationship Looks like
Union (|)Set union
Intersection (&)Set intersection
Difference (-)Set difference
Symmmetric DifferenceSet difference
Superset/Contains (>)Set difference
Subset (<)