The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Create a populated set | colors = {'red', 'green', 'blue'} | View examples |
| Create an empty set | values = set() | View examples |
| Remove duplicates | unique = set(values) | View examples |
| Test membership | if user_id in active_ids: allow() | View examples |
| Add one member | tags.add('python') | View examples |
| Add several members | tags.update(['css', 'html']) | View examples |
| Remove a required member | tags.remove('legacy') | View examples |
| Discard if present | tags.discard('legacy') | View examples |
| Combine members | all_tags = required | optional | View examples |
| Keep shared members | shared = left & right | View examples |
| Subtract members | missing = required - supplied | View examples |
| Keep non-shared members | changed = before ^ after | View examples |
| Test subset | required <= supplied | View examples |
| Test proper subset | required < supplied | View examples |
| Test for no overlap | left.isdisjoint(right) | View examples |
| Build with a comprehension | lengths = {len(word) for word in words} | View examples |
| Create an immutable set | permissions = frozenset({'read', 'write'}) | View examples |
A set stores distinct hashable objects and is optimized for membership tests and mathematical set operations. Sets are unordered, so never use their display or iteration order as a contract. Use frozenset when the collection itself must be hashable or immutable.
Step by step
Detailed examples
Create distinct collections explicitly
Set literals are concise for known values, while set(iterable) converts another collection and removes duplicates. Members must be hashable, so strings, numbers, tuples of hashable objects, and frozensets work; lists, dictionaries, and ordinary sets do not. Converting to a set discards order.
colors = {'red', 'green', 'blue', 'red'}
empty = set()
unique_numbers = set([3, 1, 3, 2])
print(sorted(colors))
print(len(empty))
print(sorted(unique_numbers)) ['blue', 'green', 'red']
0
[1, 2, 3]Choose failure behavior when removing values
Membership tests express the central strength of a set. add and update mutate in place and return None. remove is useful when absence indicates a bug because it raises KeyError; discard is appropriate for idempotent cleanup. pop removes an arbitrary member, not the earliest or smallest one.
tags = {'python'}
tags.add('testing')
tags.update(['css', 'html', 'testing'])
print('python' in tags)
tags.discard('legacy')
tags.remove('css')
print(sorted(tags)) True
['html', 'python', 'testing']Use operators for mathematical set results
Union, intersection, difference, and symmetric difference return new sets. Their named method forms can accept general iterables, while operators require set-like operands. In-place forms such as |= mutate the left operand, so use them only when callers do not depend on the original value.
before = {'search', 'export', 'alerts'}
after = {'search', 'sharing', 'alerts'}
print(sorted(before | after))
print(sorted(before & after))
print(sorted(before - after))
print(sorted(before ^ after)) ['alerts', 'export', 'search', 'sharing']
['alerts', 'search']
['export']
['export', 'sharing']Compare containment and overlap
<= and >= allow equality, while < and > require a proper subset or superset. These operators describe containment, not ordering: sets have no total order. isdisjoint can stop once it finds overlap and communicates intent better than building an intersection just to test whether it is empty.
required = {'read'}
granted = {'read', 'write'}
forbidden = {'admin', 'owner'}
print(required <= granted)
print(required < granted)
print(granted.isdisjoint(forbidden)) True
True
TrueTransform and filter into distinct results
A set comprehension has the same expression and filtering structure as a list comprehension but retains only distinct hashable results. It is useful when uniqueness is part of the result's meaning. If stable first-seen order matters, use dict.fromkeys(iterable) and convert only if set operations are later needed.
labels = [' Python ', 'CSS', 'python', ' HTML ']
normalized = {label.strip().lower() for label in labels if label.strip()}
lengths = {len(label) for label in normalized}
print(sorted(normalized))
print(sorted(lengths)) ['css', 'html', 'python']
[3, 4, 6]Use frozenset for immutable set values
frozenset supports non-mutating set operations and membership but has no add, remove, or update methods. Because it is immutable and hashable when its members are hashable, it can be a dictionary key or a member of another set. This makes it useful for unordered composite identities.
routes = {
frozenset({'read'}): '/viewer',
frozenset({'read', 'write'}): '/editor',
}
permissions = frozenset(['write', 'read'])
print(routes[permissions])
print(sorted(permissions | {'share'})) /editor
['read', 'share', 'write']Local code tester
Explore set relationships
Edit two collections and inspect their unique members, overlap, differences, and containment.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



