7

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?

Shahjalal
  • 1,163
  • 7
  • 21
  • 38
Solaman Raji
  • 170
  • 9
  • I tried with many different 2.x versions of hash on different machines right now. It shows the same result. While different versions of python3.x show a different result. – Akshay Hazari Dec 03 '15 at 06:10

1 Answers1

1

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.
Philippe Ombredanne
  • 2,017
  • 21
  • 36
  • 1
    Comment on xxHash is incorrect : result is stable across multiple different OS and architecture, be it little or big endian, 32/64 bits, posix or not, etc. – Cyan Jul 18 '16 at 00:54
  • 1
    @cyan you are right and has the author of xxHash I must thank you ++ for chiming in: I added "with some caution" as I bumped in endianness issues in the past. For instance I experienced this fist hand when porting a C Murmur 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. – Philippe Ombredanne Jul 18 '16 at 05:06