Set operations
- Version
- 3.14
- Review
- Draft
Summary#
A set holds distinct hashable values. Set operations find shared, combined or missing members. A frozenset is the immutable, hashable form.
Syntax#
left | right # union
left & right # intersection
left - right # difference
left ^ right # symmetric difference
left <= right # subset test
left.union(iterable)
Example#
granted = {"read", "write", "audit"}
required = {"read", "delete"}
print(sorted(granted | required))
print(sorted(granted & required))
print(sorted(required - granted))
print(sorted(granted ^ required))
print(required <= granted)
print(sorted(granted.intersection(["audit", "audit", "admin"])))
roles = {frozenset(["read", "write"]): "editor"}
print(roles[frozenset(["write", "read"])])
Expected output#
['audit', 'delete', 'read', 'write']
['read']
['delete']
['audit', 'delete', 'write']
False
['audit']
editor
Common mistakes#
{} creates an empty dictionary. Use set() for an empty set. Operators such as & require sets on both sides, while methods such as intersection accept any iterable. A set does not keep insertion order, so sort it before producing ordered output.
Version applicability#
The set literals, methods and operators shown work on all Python 3 releases.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0