Python - Set
Python - Set
11:11PM
enda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agenda • Agen
Frozen set
Frozenset is a built-in type in python that has the
characteristics of a set, but its elements cannot be
changed once assigned. While tuples are immutable lists,
frozensets are immutable sets.
n Header • Section Header • Section Header • Section Header • Section Header • Section Header • Section Header • Section H
# initializing A and B using frozenset function
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
This data type supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union().Being immutable, it does
not have methods that add remove or modify any elements.
Since a frozenset is immutable, you might think it can’t be the target of an augmented assignment
operator. But that's not totally true it can still perform some augmented assignments like:
a = frozenset([1, 2, 3, 4])
b = frozenset([3, 4, 5, 6])
a &= b
print(a)
>>>frozenset({3, 4})
Even though Python does not perform augmented assignments on frozensets in place. The statement a
&= b is effectively equivalent to a = a & b so because of this python isn’t modifying the original a. It is
just reassigning a to a new object, and the object a originally referenced is gone.
You can verify this with the id() function
Frozensets are useful in situations where you want to use a set, but you need an immutable object.
1) For example, you can’t define a set whose elements are also sets but If you really feel compelled to
define a set of sets you can do after converting the elements into a frozensets, because they are
immutable.
2) Likewise, in dictionaries we know a dictionary key must be immutable. You can’t use the built-in set
type as a dictionary key but if you find yourself needing to use sets as dictionary keys, you can use it
through frozensets:
>>>