Python also provides two set types, set
and frozenset
. The set
type is mutable, while frozenset
is immutable. They are unordered collections of immutable objects. Hashability is a characteristic that allows an object to be used as a set member as well as a key for a dictionary, as we'll see very soon.
Note
From the official documentation:
An object is hashable if it has a hash value which never changes during its lifetime, and can be compared to other objects. Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally. All of Python’s immutable built-in objects are hashable while mutable containers are not.
Objects that compare equally must have the same hash value. Sets are very commonly used to test for membership, so let's introduce the in
operator in the following example:
>>> small_primes = set() # empty set >>> small_primes.add(2) # adding one element at a time >>> small_primes...