Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Fix TypeError: unhashable type: ‘list’

#1
How to Fix TypeError: unhashable type: ‘list’

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;465745&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;2&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (2 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (2 votes) </div>
</div>
<p class="has-global-color-8-background-color has-background">The <code>TypeError: unhashable type: 'list'</code> usually occurs when you try to use a list object as a set element or dictionary key and Python internally passes the unhashable list into the <code>hash()</code> function. But as lists are mutable objects, they do not have a fixed hash value. The easiest way to fix this error is to use a hashable tuple instead of a non-hashable list as a dictionary key or set element.</p>
<p>We’ll show how this is done in the remaining article. The last method is a unique way to still use lists in sets or dictionary keys that you likely won’t find anywhere else, so keep reading and learn something new! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f41d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Problem Formulation and Explanation</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How to fix the <code>TypeError: unhashable type: 'list'</code> in your Python script?</p>
<p>There are two common reasons for this error:</p>
<ul>
<li>You try to use a <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> as a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a> key, or</li>
<li>You try to use a list as a <a href="https://blog.finxter.com/sets-in-python/" data-type="post" data-id="1908" target="_blank" rel="noreferrer noopener">set</a> element.</li>
</ul>
<p>This is not a trivial problem because <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">Python lists</a> are <a rel="noreferrer noopener" href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" target="_blank">mutable</a> and, therefore, not <a rel="noreferrer noopener" href="https://blog.finxter.com/python-hash-function/" target="_blank">hashable</a>.</p>
<p>Here’s the first example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [1, 2, 3]
my_dict = {}
my_dict[my_list] = 'hello Finxters!' '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 3, in &lt;module> my_dict[my_list] = 'hello Finxters!'
TypeError: unhashable type: 'list' '''</pre>
<p>And here’s the second example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
my_set = set(my_list) '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in &lt;module> my_set = set(my_list)
TypeError: unhashable type: 'list' '''</pre>
<p>As you’ve seen in the previous two code snippets, the <code>TypeError: unhashable type: 'list'</code> usually occurs when you try to use a list object as a set element or dictionary key. </p>
<p>But let’s dive deeper to find the real reason for the error:</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1fab2.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Minimal Reproducible Error Example</strong>: Lists are <a rel="noreferrer noopener" href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank">mutable</a> objects so they do not have a fixed <a rel="noreferrer noopener" href="https://blog.finxter.com/python-hash-function/" data-type="post" data-id="24483" target="_blank">hash value</a>. In fact, the error can be reproduced most easily when calling <code>hash(lst)</code> on a list object <code>lst</code>.</p>
<p>This is shown in the following minimal example that causes the error:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">hash([1, 2, 3])</pre>
<p>The output is the error message:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 1, in &lt;module> hash([1, 2, 3])
TypeError: unhashable type: 'list'</pre>
<p>Because you cannot successfully pass a list into the <code><a href="https://blog.finxter.com/python-hash-function/" data-type="post" data-id="24483" target="_blank" rel="noreferrer noopener">hash()</a></code> function, you cannot directly use lists as set elements or dictionary keys. </p>
<p>But let’s dive into some solutions to this problem!</p>
<h2>Method 1: Use Tuple Instead of List as Dictionary Key</h2>
<p class="has-global-color-8-background-color has-background">The easiest way to fix the <code>TypeError: unhashable type: 'list'</code> is to use a hashable tuple instead of a non-hashable list as a dictionary key. For example, whereas <code>d[my_list]</code> will raise the error, you can simply use <code>d[tuple(my_list)]</code> to fix the error.</p>
<p>Here’s an example of what you can do instead:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [1, 2, 3]
my_dict = {}
my_dict[tuple(my_list)] = 'hello Finxters!' print(my_dict)
# {(1, 2, 3): 'hello Finxters!'}
</pre>
<p>The error may also occur when you try to use a list as a set element. Next, you’ll learn what to do in that case:</p>
<h2>Method 2: Use Tuple Instead of List as Set Element</h2>
<p class="has-global-color-8-background-color has-background">To fix the <code>TypeError: unhashable type: 'list'</code> when trying to use a list as a set element is to use a hashable tuple instead of a non-hashable list. For example, whereas <code>set.add([1, 2])</code> will raise the error, you can simply use <code>set.add((1, 2))</code> or <code>set.add(tuple([1, 2]))</code> to fix the error.</p>
<p>Here’s a minimal example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="6" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_set = set() # Error: my_set.add([1, 2]) # This is how to resolve the error:
my_set.add((1, 2))
# Or: my_set.add(tuple([1, 2])) print(my_set)
# {(1, 2)}
</pre>
<p>If you want to convert a list of lists to a set, you can check out my detailed tutorial on the Finxter blog:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Related Tutorial</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-convert-a-list-of-lists-to-a-set-in-python/" data-type="post" data-id="464395" target="_blank">How to convert a list of lists to a set?</a></p>
<h2>Method 3: Use String Representation of List as Set Element or Dict Key</h2>
<p class="has-global-color-8-background-color has-background">To fix the <code>TypeError: unhashable type: 'list'</code>, you can also use a string representation of the list obtained with <code><a href="https://blog.finxter.com/python-str-function/" data-type="post" data-id="23735" target="_blank" rel="noreferrer noopener">str(my_list)</a></code> as a set element or dictionary key. Strings are hashable and immutable, so Python won’t raise the error when using this approach.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [1, 2, 3] # 1. Use str repr of list as dict key:
d = {}
d[str(my_list)] = 'hello Finxters' # 2. Use str repr of list as set element:
s = set()
s.add(str(my_list))
</pre>
<p>In both cases, we used the string representation of the list instead of the list itself. The string is immutable and hashable and it fixes the error.</p>
<p>But what if you really need a mutable set or dictionary key? Well, you shouldn’t but you can by using this approach: </p>
</p>
<h2>Method 4: Create Hashable Wrapper List Class</h2>
<p class="has-global-color-8-background-color has-background">You can still use a mutable list as a dictionary key, set element, or argument of the <code>hash()</code> function by defining a wrapper class, say HackedList, that overrides the <code><a href="https://blog.finxter.com/python-__hash__-magic-method/" data-type="post" data-id="38118" target="_blank" rel="noreferrer noopener">__hash__()</a></code> <a href="https://blog.finxter.com/python-dunder-methods-cheat-sheet/" data-type="post" data-id="35586" target="_blank" rel="noreferrer noopener">dunder method</a>.</p>
<p>Python’s <a rel="noreferrer noopener" href="https://blog.finxter.com/python-built-in-functions/" target="_blank">built-in</a> <code><strong>hash(object)</strong></code> function takes one object as an argument and returns its hash value as an integer. You can view this hash value as a unique fingerprint of this object. </p>
<p>The Python <code>__hash__()</code> method implements the built-in <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-hash-function/" target="_blank">hash()</a></code> function.</p>
<p>Here’s the minimal code example that creates a wrapper class HackedList that overrides the <code>__hash__()</code> dunder method so you can use an instance of <code>HackedList</code> as a dictionary key, set element, or just as input to the <code>hash()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [1, 2, 3] class HackedList: def __init__(self, lst): self.lst = lst def __hash__(self): return len(self.lst) my_hacked_list = HackedList(my_list) # 1. Pass hacked list into hash() function:
print(hash(my_hacked_list)) # Output: 3 # 2. Use hacked list as dictionary key:
d = dict()
d[my_hacked_list] = 'hello Finxters' # 3: Use hacked list as set element:
s = set()
s.add(my_hacked_list)
</pre>
<p>Here’s the content of the dictionary and set defined previously:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{&lt;__main__.HackedList object at 0x0000016CFB0BDFA0>: 'hello Finxters'}
{&lt;__main__.HackedList object at 0x0000016CFB0BDFA0>}</pre>
<p>If you want to fix the ugly output, you can additionally define the <code><a href="https://blog.finxter.com/python-__str__/" data-type="post" data-id="72362" target="_blank" rel="noreferrer noopener">__str__()</a></code> and <code><a href="https://blog.finxter.com/python-__repr__/" data-type="post" data-id="97521" target="_blank" rel="noreferrer noopener">__repr__()</a></code> magic methods like so:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="11-12, 14-15" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_list = [1, 2, 3] class HackedList: def __init__(self, lst): self.lst = lst def __hash__(self): return len(self.lst) def __str__(self): return str(self.lst) def __repr__(self): return str(self.lst) my_hacked_list = HackedList(my_list) # 1. Pass hacked list into hash() function:
print(hash(my_hacked_list)) # Output: 3 # 2. Use hacked list as dictionary key:
d = dict()
d[my_hacked_list] = 'hello Finxters' # 3: Use hacked list as set element:
s = set()
s.add(my_hacked_list) print(d)
print(s)
</pre>
<p>Beautiful output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{[1, 2, 3]: 'hello Finxters'}
{[1, 2, 3]}</pre>
<h2>Summary</h2>
<p>The five most Pythonic ways to convert a list of lists to a set in Python are:</p>
<ul>
<li><a href="https://blog.finxter.com/how-to-fix-typeerror-unhashable-type-list/#Method_1_Use_Tuple_Instead_of_List_as_Dictionary_Key"><strong>Method 1</strong>: Use Tuple Instead of List as Dictionary Key</a></li>
<li><a href="https://blog.finxter.com/how-to-fix-typeerror-unhashable-type-list/#Method_2_Use_Tuple_Instead_of_List_as_Set_Element"><strong>Method 2</strong>: Use Tuple Instead of List as Set Element</a></li>
<li><a href="https://blog.finxter.com/how-to-fix-typeerror-unhashable-type-list/#Method_3_Use_String_Representation_of_List_as_Set_Element_or_Dict_Key"><strong>Method 3</strong>: Use String Representation of List as Set Element or Dict Key</a></li>
<li><a href="https://blog.finxter.com/how-to-fix-typeerror-unhashable-type-list/#Method_4_Create_Hashable_Wrapper_List_Class"><strong>Method 4</strong>: Create Hashable Wrapper List Class</a></li>
</ul>
<p>Feel free to check out more free tutorials and cheat sheets for learning and improving your Python skills in our free email academy:</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Nerd Humor</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="733" height="913" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-72.png" alt="" class="wp-image-410345" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-72.png 733w, https://blog.finxter.com/wp-content/uplo...41x300.png 241w" sizes="(max-width: 733px) 100vw, 733px" /><figcaption><em>Oh yeah, I didn’t even know they renamed it the Willis Tower in 2009, because I know a normal amount about skyscrapers.</em> — <a rel="noreferrer noopener" href="https://imgs.xkcd.com/comics/or_whatever_2x.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/or_whatever_2x.png" target="_blank">xkcd</a> (source)</figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/07/...type-list/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016