I was practicing tuple hashing. In there I was working on Python 2.7. Below is the code:
num = int(raw_input())
num_list = [int(x) for x in raw_input().split()]
print(hash(tuple(num_list)))
The above code results in
>>> 2
>>> 1 2
>>> 3713081631934410656
But at my local PC where I am using Python 3.4 the answer is
>>> 1299869600
The code is accepted but I could not find out what causes the different results. Is this for different version of Python?
The hash()
may return different values for the same object on different OS, architectures, Python implementations and Python versions.
It is designed to be used only within a single Python session, not across sessions or machines. So you should never rely on the value of hash()
beyond this.
If you need hashing that yields the same results everywhere, consider checksums such as:
- MD5 or SHA1,
- xxHash which per its author provides stable results across multiple OS and architecture, be it little or big endian, 32/64 bits, posix or not, etc.)
- or with some caution Murmur as some versions may yield different results on different architectures. For instance I experienced this fist hand when porting a C Murmur2 to an IBM S390 Linux install (of all odd places!). To avoid issues I ended instead coding a slow but arch-independent pure Python implementation on that OS rather than a C implementation.