A validation script deduplicates status codes before checking allowed values.
What You Need to Understand
set(iterable) constructs a mutable set of unique hashable values, while frozenset(iterable) creates an immutable set. Both accept an iterable and can be called with no arguments.
When to Use It
A validation script deduplicates status codes before checking allowed values.
Step-by-Step Python Example
values = ["ok", "retry", "ok"]
editable = set(values)
fixed = frozenset(values)
editable.add("failed")
print(sorted(editable))
print(sorted(fixed))
How the Example Works
The mutable set accepts a new entry. The frozen set remains a two-member snapshot.
Example Output
['failed', 'ok', 'retry']
['ok', 'retry']
frozenset({10})
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
editable = set()
editable.add(10)
print(frozenset(editable))
Important Behavior and Edge Cases
An empty set must be written set(), because {} creates an empty dictionary. Neither constructor accepts unhashable members such as lists.
Try It Yourself
Create an empty set, add an item, then create a frozen copy.
Common Beginner Mistakes
- An empty set must be written
set(), because{}creates an empty dictionary. Neither constructor accepts unhashable members such as lists. - Depending on set iteration order or using a set when duplicates and original positions must be preserved.
Key Takeaways
set(iterable)constructs a mutable set of unique hashable values, whilefrozenset(iterable)creates an immutable set.- The mutable set accepts a new entry.
- An empty set must be written
set(), because{}creates an empty dictionary.