In Python, comprehensions provide a concise way to create iterable objects. We have previously learned about list, tuple, set, dictionary, and generator comprehensions, and today we will look at another useful comprehension – the frozenset comprehension.A frozenset is an immutable set type in Python, and its main difference from a regular set is that it cannot be modified after creation, allowing it to be used as a key in dictionaries or as elements of other sets.When creating a one-dimensional frozenset, comprehensions can make the code more concise:
sample = frozenset([0, 1, 2, 3, 4, 5, 6, 7])# Using frozenset comprehensionA = frozenset(x**2 for x in sample)print(A)# Output: frozenset({0, 1, 4, 36, 9, 16, 49, 25})
If we do not use comprehensions, we need to write more code:
sample = frozenset([0, 1, 2, 3, 4, 5, 6, 7])# Method 1: Create a list first and then convertA = []for x in sample: A.append(x**2)A = frozenset(A)# Method 2: Merge step by stepA = frozenset()for x in sample: A = A.union({x**2})print(A)# Output: frozenset({0, 1, 4, 36, 9, 16, 49, 25})
For nested structures, frozenset comprehensions are also applicable:
sample = frozenset([frozenset([0, 1, 2, 3]), frozenset([4, 5, 6, 7])])# Using frozenset comprehensionA = frozenset([frozenset(y**2 for y in x) for x in sample])print(A)# Output: frozenset({frozenset({16, 25, 36, 49}), frozenset({0, 1, 4, 9})})
However, if we do not use comprehensions, it becomes much more complex:
sample = frozenset([frozenset([0, 1, 2, 3]), frozenset([4, 5, 6, 7])])# Method 1: Nested loopsA = []for i, x in enumerate(sample): A.append([]) for y in x: A[i].append(y**2) A[i] = frozenset(A[i])A = frozenset(A)# Method 2: Using a generatorA = frozenset()for x in sample: def func(x): for y in x: yield y**2 A = A.union(frozenset([frozenset(func(x))]))A = frozenset(A)print(A)# Output: frozenset({frozenset({16, 25, 36, 49}), frozenset({0, 1, 4, 9})})
Even for more complex three-dimensional structures, comprehensions can still maintain code simplicity:
sample = frozenset([ frozenset([frozenset([0, 1]), frozenset([2, 3])]), frozenset([frozenset([4, 5]), frozenset([6, 7])])])# Using frozenset comprehensionA = frozenset(frozenset(frozenset(z**2 for z in y) for y in x) for x in sample)print(A)# Output:# frozenset({# frozenset({frozenset({16, 25}), frozenset({49, 36})}),# frozenset({frozenset({9, 4}), frozenset({0, 1})})# })
In conclusion, frozenset comprehensions provide a concise and readable way to create immutable sets, especially when dealing with nested structures, significantly reducing code size and improving readability. Those interested should definitely try it out themselves.