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.
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.add(3) >>> small_primes.add(5) >>> small_primes {2, 3, 5} >>> small_primes.add(1) # Look what I've done, 1 is not a prime! >>> small_primes {1, 2, 3, 5} >>> small_primes.remove(1) # so let's remove it >>> 3 in small_primes # membership...