Sets are backed by the same hash-table machinery as dictionaries, so checking whether a value is in a set runs in average O(1) time regardless of the set's size, unlike a list where membership testing is O(n). Sets also implement the standard mathematical set operations — union, intersection, difference, and symmetric difference — as both operators and named methods.
1Understanding Sets
Sets are backed by the same hash-table machinery as dictionaries, so checking whether a value is in a set runs in average O(1) time regardless of the set's size, unlike a list where membership testing is O(n). Sets also implement the standard mathematical set operations — union, intersection, difference, and symmetric difference — as both operators and named methods.
Swap a list for a set when you're doing a lot of membership checks in a loop — it turns an O(n) scan into an O(1) lookup on average.
seen = set()
for n in [1, 2, 2, 3, 1]:
if n not in seen:
seen.add(n)
print(seen)2Practical Example
Here is a real-world application of Sets showing how it is used in production Python code.
required = {"id", "name", "email"}
provided = {"id", "name"}
missing = required - provided
print(missing)3Best Practices
Follow these guidelines when working with Sets:
1. Use a set instead of a list when you need fast membership testing and don't care about order or duplicates
2. Use set operators (|, &, -) instead of manual loops when comparing two collections
3. Use frozenset instead of set when the collection needs to be hashable itself, e.g. as a dictionary key
Tip: Swap a list for a set when you're doing a lot of membership checks in a loop — it turns an O(n) scan into an O(1) lookup on average.
seen = set()
for n in [1, 2, 2, 3, 1]:
if n not in seen:
seen.add(n)
print(seen)