Search code examples
pythonhashnegative-integer

The hash of -1 is equal to the hash of -2 in python


Why do the negative integers -1 and -2 have the same hash?

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

Solution

  • No, it's not a bug, as stated in the help text of the hash function:

    >>> help(hash)
    Help on built-in function hash in module builtins:
    
    hash(obj, /)
        Return the hash value for the given object.
        
        Two objects that compare equal must also have the same hash value, but the
        reverse is not necessarily true.
    

    i.e., It's not necessarily true that two objects that have the same hash value compare equal.

    Interestingly, the documentation has a different wording and doesn't explicitly mention this, it only says

    Numeric values that compare equal have the same hash value