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

Question:

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

>>> hash(-1)
-2
>>> hash(-2)
-2
Asked By: amitjans

||

Answers:

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

Answered By: mkrieger1
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.