8.1 set-tuple
The frozenset
collection is an
immutable version of set
. It gives you all the benefits of a set, but doesn't let you change its elements after it's created. frozenset
is super handy when you need to store unique items and ensure the set isn't altered.
Creating a frozenset
To whip up a frozenset
, you can call the frozenset()
function, passing in an iterable (like a list, tuple, string, etc.).
Examples:
Creating frozenset
from a list
# Creating frozenset from a list
fset1 = frozenset([1, 2, 3, 4])
print(fset1) # Output: frozenset({1, 2, 3, 4})
Creating frozenset
from a string
# Creating frozenset from a string
fset2 = frozenset("hello")
print(fset2) # Output: frozenset({'h', 'e', 'l', 'o'})
Creating an empty frozenset
# Creating an empty frozenset
fset3 = frozenset()
print(fset3) # Output: frozenset()
8.2 Main methods of frozenset
frozenset
supports most methods available for mutable sets (set)
, but since it's immutable, any methods that modify the set aren't available.
Examples:
Union of sets (union)
fset1 = frozenset([1, 2, 3, 4])
fset2 = frozenset([3, 4, 5, 6])
# Union of sets (union)
print(fset1 | fset2) # Output: frozenset({1, 2, 3, 4, 5, 6})
print(fset1.union(fset2)) # Output: frozenset({1, 2, 3, 4, 5, 6})
Intersection of sets (intersection)
fset1 = frozenset([1, 2, 3, 4])
fset2 = frozenset([3, 4, 5, 6])
# Intersection of sets (intersection)
print(fset1 & fset2) # Output: frozenset({3, 4})
print(fset1.intersection(fset2)) # Output: frozenset({3, 4})
Difference of sets (difference)
fset1 = frozenset([1, 2, 3, 4])
fset2 = frozenset([3, 4, 5, 6])
# Difference of sets (difference)
print(fset1 - fset2) # Output: frozenset({1, 2})
print(fset1.difference(fset2)) # Output: frozenset({1, 2})
Symmetric difference (symmetric difference)
fset1 = frozenset([1, 2, 3, 4])
fset2 = frozenset([3, 4, 5, 6])
# Symmetric difference (symmetric difference)
print(fset1 ^ fset2) # Output: frozenset({1, 2, 5, 6})
print(fset1.symmetric_difference(fset2)) # Output: frozenset({1, 2, 5, 6})
8.3 Using frozenset
frozenset
is handy in these situations:
Using as a dictionary key:
Since frozenset
is immutable, you can totally use it as a dictionary key.
fset1 = frozenset([1, 2, 3])
fset2 = frozenset([3, 4, 5])
d = {fset1: "first", fset2: "second"}
print(d) # Output: {frozenset({1, 2, 3}): 'first', frozenset({3, 4, 5}): 'second'}
Storing immutable sets:
If you need to make a set of unique items that won't be changed later on, frozenset
's a great choice.
Data safety:
Using frozenset
ensures the data won't get accidentally changed while your script is running.
GO TO FULL VERSION