5.6 Set Data Types
Python's set and frozenset — unordered collections of unique, hashable values — and the classic one-line list-deduplication pattern.
set
What Is It?
A mutable, unordered collection of unique, hashable values.
Why Is It Used?
Automatic deduplication and fast (O(1) average) membership testing — far faster than checking in on a list for large collections.
>>> s = {1, 2, 3, 2, 1} # duplicates are automatically dropped
>>> s
{1, 2, 3}
frozenset
The immutable counterpart to set — same behavior, but can’t be modified after creation, which makes it hashable and therefore usable as a dict key or set member itself.
>>> fs = frozenset([1, 2, 3])
>>> fs.add(4)
Traceback (most recent call last):
AttributeError: 'frozenset' object has no attribute 'add'
Unique Values
The most common practical use of set: deduplicating a list in one line.
>>> ips = ["10.0.0.1", "10.0.0.2", "10.0.0.1"]
>>> unique_ips = set(ips)
>>> unique_ips
{'10.0.0.1', '10.0.0.2'}
Quick Interview Answer
“
setis a mutable, unordered collection of unique, hashable values — it deduplicates automatically and gives O(1) average membership testing, versus O(n) for a list.frozensetis its immutable counterpart, which makes it hashable and therefore usable as a dict key or as a member of another set.set(some_list)is the standard one-line way to deduplicate.”
Common Mistakes
- Trying to add to a
frozensetafter creation — it has no.add(), since it’s immutable by design. - Relying on set ordering — sets are unordered, so iteration order isn’t guaranteed the way it is for a list or (since 3.7) a dict.
- Putting an unhashable value (like a
list) into a set, raisingTypeError: unhashable type.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form