Search code examples
pythonsetfrozenset

Different python frozensets with same hash value


My understanding is that hashing two different frozensets (immutable Python sets), which need to contain hashable objects, should lead to two different hashes. Why do I get the output below for two different frozensets?

In [11]: a
Out[11]: frozenset({(2, -2), (2, -1), (3, -2), (3, -1)})

In [12]: b
Out[12]: frozenset({(4, -2), (4, -1), (5, -2), (5, -1)})

In [13]: hash(a)
Out[13]: 665780563440688

In [14]: hash(b)
Out[14]: 665780563440688

Solution

  • You seem to have stumbled upon two frozensets with equal hash codes and different contents. This is not so strange as it may seem as the property of hash codes are that they are guaranteed to be equal for equal objects and probably different for non-equal objects.

    From the Python docs:

    hash(object) -> integer

    Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely.

    The absolute easiest example of this are the numbers -1 and -2 which have the same hash code in python:

    >>> print(hash(-1))
    -2
    >>> print(hash(-2))
    -2