Loading lesson...
Frozensets, comprehensions, patterns
Frozensets, comprehensions, patterns
Topics covered: Frozensets: Immutable Sets, Set Comprehensions, Performance: When to Use Sets
A frozenset is an immutable version of a set. Once created, a frozenset cannot be modified: you cannot add or remove elements. This immutability might seem like a limitation, but it has an important consequence that unlocks powerful patterns: frozensets are hashable, meaning they can be used as dictionary keys or as elements of other sets. To understand why immutability enables hashing, recall that hash tables (the underlying data structure for both dictionaries and sets) rely on objects having
Set comprehensions provide a concise, expressive way to create sets from iterables with optional filtering and transformation. If you are familiar with list comprehensions, set comprehensions follow the exact same syntax but use curly braces instead of square brackets. The result is a set with all duplicates automatically removed. The comprehension accomplishes the same result in one readable line. Both produce identical sets of squares from 1 to 25. The comprehension form is generally preferred
Choosing between sets and lists affects both correctness and performance. Understanding the time complexity of common operations helps you make informed decisions. The wrong choice can turn an efficient algorithm into a painfully slow one. The critical difference is membership testing. For a list with 1 million elements, checking if an item exists requires scanning up to 1 million elements in the worst case. For a set, the same check is nearly instant regardless of size because sets use hash tab