Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Python Does What?!: first hash past the post

$
0
0
Numeric types in Python have the interesting property that their hash() is often their value:

>>> hash(1)
1
>>> hash(1.0)
1

Python also considers floating point and integers of the same value to be equal:

>>> 1 == 1.0
True

Two things with the same hash that are equal count as the same key in a dict:

>>> 1 in {1.0: 'cat'}
True

However, it is possible for the key to be either an int or a float:

>>> {1: 'first'}
{1: 'first'}
>>> {1.0: 'second'}
{1.0: 'second'}

Whichever key is used first sticks.  Later writes to the dict can change the value, but the int or float key remains:

>>> {1: 'first', 1.0: 'second'}
{1: 'second'}
>>> {1.0: 'first', 1: 'second'}
{1.0: 'second'}

Viewing all articles
Browse latest Browse all 22462

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>