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
As noted by many, Python's hash is not consistent anymore (as of version 3.3), as a random PYTHONHASHSEED is now used by default (to address security concerns, as explained in this excellent answer).
Frozen set being immutable are hashable, can be used as a “key” for dictionaries or elements for another set object. Frozen set is constructed using “frozenset()” function.
Unequal objects may have the same hash values. Equal objects need to have the same id values. Whenever obj1 is obj2 is called, the id values of both objects is compared, not their hash values.
Python immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id .
You seem to have stumbled upon two frozenset
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With