{"id":6209,"date":"2020-05-31T06:59:28","date_gmt":"2020-05-31T06:59:28","guid":{"rendered":"https:\/\/www.askpython.com\/?p=6209"},"modified":"2022-08-06T13:14:52","modified_gmt":"2022-08-06T13:14:52","slug":"python-hash-function","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/built-in-methods\/python-hash-function","title":{"rendered":"Using the Python hash() function"},"content":{"rendered":"\n<p>Hello everyone! In today&#8217;s article, we&#8217;ll be looking at Python&#8217;s in-built <code>hash()<\/code> function. The Python <code>hash()<\/code> function computes the hash value of a Python object. But the language uses this to a large extent.<\/p>\n\n\n\n<p>Let&#8217;s understand more about this function, using some examples!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Syntax of Python hash()<\/h2>\n\n\n\n<p>This function takes in an <em>immutable<\/em> <a href=\"https:\/\/www.askpython.com\/python\/oops\/python-classes-objects\" class=\"rank-math-link\">Python object<\/a>, and returns the hash value of this object.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nvalue = hash(object)\n<\/pre><\/div>\n\n\n<p>Remember that the hash value is dependent on a hash function, (from <code>__hash__()<\/code>), which <code>hash()<\/code> internally calls. This hash function needs to be good enough such that it gives an almost random distribution.<\/p>\n\n\n\n<p>Well, why do we want a hash function to randomize its values to such a large extent? This is because we want the hash function to map almost every key to a unique value.<\/p>\n\n\n\n<p>If your values are randomly distributed, there will be very little chance of two different keys being mapped to the same value, which is what we want!<\/p>\n\n\n\n<p>Now, let&#8217;s look at the <code>hash()<\/code> function in use, for simple objects like integers, floats and strings.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using the hash() function &#8211; Some Examples<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nint_hash = hash(1020)\n\nfloat_hash = hash(100.523)\n\nstring_hash = hash(&quot;Hello from AskPython&quot;)\n\nprint(f&quot;For {1020}, Hash : {int_hash}&quot;)\nprint(f&quot;For {100.523}, Hash: {float_hash}&quot;)\nprint(f&quot;For {&#039;Hello from AskPython&#039;}, Hash: {string_hash}&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nFor 1020, Hash : 1020\nFor 100.523, Hash: 1205955893818753124\nFor Hello from AskPython, Hash: 5997973717644023107\n<\/pre><\/div>\n\n\n<p>As you can observe, integers have the same hash value as their original value. But the values are obviously different for the float and the string objects.<\/p>\n\n\n\n<p>Now, it won&#8217;t be very safe if the same object (except integers\/floats) always has the same hash value. So, if you run the above snippet again, you&#8217;ll notice different values!<\/p>\n\n\n\n<p>For example, this is my output when I run the same snippet for the second time.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nFor 1020, Hash : 1020\nFor 100.523, Hash: 1205955893818753124\nFor Hello from AskPython, Hash: -7934882731642689997\n<\/pre><\/div>\n\n\n<p>As you can see, the value is changed for the string! This is a good thing because it prevents the same object from being potentially accessed by someone! The hash value remains constant only until the duration of your program.<\/p>\n\n\n\n<p>After that, it keeps changing every time you run your program again.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why cannot we use hash() on mutable objects?<\/h2>\n\n\n\n<p>Now, remember that we mentioned earlier about <code>hash()<\/code> being used only on <em>immutable<\/em> objects. What does this mean?<\/p>\n\n\n\n<p>This means that we cannot use <code>hash()<\/code> on mutable objects like lists, sets, dictionaries, etc.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nprint(hash(&#x5B;1, 2, 3]))\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nTypeError: unhashable type: &#039;list&#039;\n<\/pre><\/div>\n\n\n<p>Why is this happening? Well, it would be troublesome for the program to keep changing the hash value every time the value of a mutable object changes.<\/p>\n\n\n\n<p>This will make it very time consuming to keep updating the hash value again. If you do this, then Python needs to take a lot of time to keep referring to the same object, since the references will keep changing!<\/p>\n\n\n\n<p>Due to this, we cannot hash mutable objects using <code>hash()<\/code>, since they only have a single value, which is hidden from us, so that the program can internally keep a reference to it.<\/p>\n\n\n\n<p>However, we <em>can<\/em> use <code>hash()<\/code> on an immutable tuple. This is a <a href=\"https:\/\/www.askpython.com\/python\/tuple\/python-tuple\" class=\"rank-math-link\">tuple<\/a> that consists of only immutable objects, like ints, floats, etc.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; print(hash((1, 2, 3)))\n2528502973977326415\n\n&gt;&gt;&gt; print(hash((1, 2, 3, &quot;Hello&quot;)))\n-4023403385585390982\n\n&gt;&gt;&gt; print(hash((1, 2, &#x5B;1, 2])))\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: unhashable type: &#039;list&#039;\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using hash() on a Custom Object<\/h2>\n\n\n\n<p>Since the default Python <code>hash()<\/code> implementation works by overriding the <code>__hash__()<\/code> method, we can create our own <code>hash()<\/code> method for our custom objects, by overriding <code>__hash__()<\/code>, provided that the relevant attributes are immutable.<\/p>\n\n\n\n<p>Let&#8217;s create a class <code>Student<\/code> now.<\/p>\n\n\n\n<p>We&#8217;ll be overriding the <code>__hash__()<\/code> method to call <code>hash()<\/code> on the relevant attributes. We will also be implementing the <code>__eq__()<\/code> method, for checking equality between the two custom objects.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Student:\n    def __init__(self, name, id):\n        self.name = name\n        self.id = id\n\n    def __eq__(self, other):\n        # Equality Comparison between two objects\n        return self.name == other.name and self.id == other.id\n\n    def __hash__(self):\n        # hash(custom_object)\n        return hash((self.name, self.id))\n\nstudent = Student(&#039;Amit&#039;, 12)\nprint(&quot;The hash is: %d&quot; % hash(student))\n\n# We&#039;ll check if two objects with the same attribute values have the same hash\nstudent_copy = Student(&#039;Amit&#039;, 12)\nprint(&quot;The hash is: %d&quot; % hash(student_copy))\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nThe hash is: 154630157590\nThe hash is: 154630157597\n<\/pre><\/div>\n\n\n<p>We can indeed observe the hash of our custom object. Not only that; two different objects even with the same attribute values, have different hash values!<\/p>\n\n\n\n<p>This is indeed what we want to expect from a hash function, and <code>hash()<\/code> has successfully given us that!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>We learned about using the Python <code>hash()<\/code> function. This is very useful for the program to maintain references to each object, using a special integer value.<\/p>\n\n\n\n<p>We also saw how we could make <code>hash()<\/code> work on custom objects, provided it&#8217;s attributes are immutable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Python hash() function<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Hello everyone! In today&#8217;s article, we&#8217;ll be looking at Python&#8217;s in-built hash() function. The Python hash() function computes the hash value of a Python object. But the language uses this to a large extent. Let&#8217;s understand more about this function, using some examples! Basic Syntax of Python hash() This function takes in an immutable Python [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":6220,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-6209","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-built-in-methods"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6209","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=6209"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6209\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/6220"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=6209"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=6209"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=6209"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}