How do sets and frozensets work in Python?
· Category: Python Programming
Short answer
A Python set is an unordered collection of unique, hashable elements. Sets support mathematical operations like union, intersection, and difference. A frozenset is an immutable version of a set.
Steps
- Create a set:
s = {1, 2, 3}ors = set([1, 2, 3]). - Add or remove items:
.add(),.discard(),.remove(). - Perform set operations:
|,&,-,^.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
Tips
- Convert a list to a set to remove duplicates:
unique = list(set(items)). - Set membership testing (
x in s) is O(1) on average, making it much faster than lists for large collections. - Use frozensets when you need a set as a dictionary key or an element of another set.
- Set comprehensions work like list comprehensions:
{x for x in items if x > 0}.
Common issues
{}creates an empty dictionary, not a set; useset()for an empty set.- Sets are unordered, so they do not support indexing or slicing.
- Adding an unhashable type (like a list) to a set raises a
TypeError.