Sets and Set Operations
A collection with no duplicates and no order, built for membership tests and for comparing two groups.
Overview
What a set gives up, and what it buys
Write a set with braces:
seen = {"red", "green", "red", "blue"}
Three items come out, not four: duplicates collapse silently. Print it twice and the order may differ, because there is no order to preserve.
In exchange, x in some_set is roughly constant time. On a list, the same question is a scan: Python looks at each element until it finds a match or runs out. On a few dozen items nobody notices. On two hundred thousand, the difference is milliseconds against microseconds, and the second program on this page measures it rather than asserting it.
sets.py
set_algebra.py
Worth knowing
{} is an empty dict, not an empty set. Use set().& intersection, | union, - difference, ^ in one but not both.