Sub topic 3
Python Sets: In-Place Operations and Practical Uses
This chapter assumes basic Python syntax, loops, the in operator, and familiarity with lists, dictionaries, mutable objects, and immutable objects.
In-place operations and update methods
Set operators can replace a set’s value in place. The original set object remains available to other references.
allowed = {"read", "write"}
requested = {"write", "delete"}
allowed |= requested
print(allowed) # {'read', 'write', 'delete'}
allowed &= {"read", "write"}
print(allowed) # {'read', 'write'}The named update methods accept any iterable:
| Operation | Operator | Method | Column |
|---|---|---|---|
| Union | ` | =` | `update()` |
| Intersection | `&=` | `intersection_update()` | |
| Difference | `-=` | `difference_update()` | |
| Symmetric difference | `^=` | `symmetric_difference_update()` |
Use these methods when you want to mutate an existing set. Use a | b when you want a new set instead.
Set comprehensions
A set comprehension builds a set from an expression. Duplicate results are removed automatically.
numbers = {-3, -2, -1, 0, 1, 2, 3}
positive_squares = {n * n for n in numbers if n > 0}
print(positive_squares) # {1, 4, 9}Practical uses: deduplication and fast lookups
Convert an iterable to a set when order does not matter and only uniqueness matters.
visits = ["home", "shop", "home", "about"]
unique_pages = set(visits)
print(unique_pages)
blocked = {"guest", "test"}
user = "guest"
if user in blocked:
print("Access denied")A set is usually a better choice than a list for repeated membership tests. A list preserves order, while a set focuses on unique values and lookup speed.
`frozenset`: immutable sets
A frozenset cannot be changed after creation. Because it is immutable and hashable, it can be a dictionary key or an element of another set.
permissions = frozenset({"read", "write"})
roles = {permissions: "editor"}
print(roles[permissions]) # editorWhy sets are fast: hash tables
Sets use a hash table. Python hashes each element and uses that hash to locate it. Membership tests are typically constant time, written as O(1), although collisions or unusual workloads can affect performance.
Common pitfalls
- Set iteration order is not a contract. Do not rely on it for output or logic.
{}creates an empty dictionary. Writeset()for an empty set.- Elements must be hashable. Tuples of hashable values work; lists and dictionaries do not.
remove(x)raisesKeyErrorwhenxis absent. Usediscard(x)for silent removal.
Exercise
Which method removes every element from current that also appears in expired, without creating a new set?
Show answer
current.difference_update(expired).