简体   繁体   中英

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

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.

ie, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM