bterwijn

bterwijn

Practical Programming, Third Edition: immutable values are not necessarily unhashable (209)

On page 209 it says: “mutable values are unhashable”
However, mutability and hash-ability are separate properties. A type is hash-able when its hash function is defined. A counter example that shows a mutable list that gets hashed and added as key to a dict:

class mylist(list): # mylist (mutable) is a list with a __hash__ function

    def __hash__(self):
        hash = 0
        for i in self:
            hash ^= i
        return hash

ml= mylist()
ml.append(1)
ml.append(2)
ml.append(3)
print( ml ) # [1, 2, 3]

mydict={ ml:100, mylist([4,5,6]):200}
print( mydict ) # {[1, 2, 3]: 100, [4, 5, 6]: 200}

print( mydict[ml] ) # 100
print( mydict[mylist([4,5,6])] ) # 200
print( mylist([6,7,8]) in mydict) # False

Also a typo:
TypeError: unhashable type: ‘set’ => TypeError: unhashable type: ‘list’

First Post!

emildepp

emildepp

@jmontojo

The “TypeError: unhashable type: ‘list’” error message in Python occurs when you try to use a mutable object (such as a list) as a key in a dictionary. Since dictionaries use keys to index values, keys must be hashable objects, meaning they must be immutable (i.e. their value cannot be changed). Lists are mutable, so they cannot be used as dictionary keys. To fix the error, use an immutable object like a tuple, string, or number as the dictionary key instead.

To resolve the TypeError: unhashable type: ‘list’ error, you need to use an immutable object as a key in a dictionary instead of a mutable one like a list. For example, you can use tuples, strings, or numbers as keys, which are all hashable objects.

d = {[1, 2, 3]: "list_key"} //Using a list as a key in a dictionary
//This will raise the TypeError: unhashable type: 'list' error
d = {(1, 2, 3): "tuple_key"} //Using a tuple as a key in a dictionary
//This will work fine as tuples are hashable

Where Next?

Popular Pragmatic Bookshelf topics Top

johnp
Running the examples in chapter 5 c under pytest 5.4.1 causes an AttributeError: ‘module’ object has no attribute ‘config’. In particula...
New
jeffmcompsci
Title: Design and Build Great Web APIs - typo “https://company-atk.herokuapp.com/2258ie4t68jv” (page 19, third bullet in URL list) Typo:...
New
jskubick
I found an issue in Chapter 7 regarding android:backgroundTint vs app:backgroundTint. How to replicate: load chapter-7 from zipfile i...
New
digitalbias
Title: Build a Weather Station with Elixir and Nerves: Problem connecting to Postgres with Grafana on (page 64) If you follow the defau...
New
brunogirin
When I run the coverage example to report on missing lines, I get: pytest --cov=cards --report=term-missing ch7 ERROR: usage: pytest [op...
New
New
taguniversalmachine
Hi, I am getting an error I cannot figure out on my test. I have what I think is the exact code from the book, other than I changed “us...
New
s2k
Hi all, currently I wonder how the Tailwind colours work (or don’t work). For example, in app/views/layouts/application.html.erb I have...
New
a.zampa
@mfazio23 I’m following the indications of the book and arriver ad chapter 10, but the app cannot be compiled due to an error in the Bas...
New
roadbike
From page 13: On Python 3.7, you can install the libraries with pip by running these commands inside a Python venv using Visual Studio ...
New

Other popular topics Top

AstonJ
What chair do you have while working… and why? Is there a ‘best’ type of chair or working position for developers?
New
New
AstonJ
Thanks to @foxtrottwist’s and @Tomas’s posts in this thread: Poll: Which code editor do you use? I bought Onivim! :nerd_face: https://on...
New
AstonJ
Inspired by this post from @Carter, which languages, frameworks or other tech or tools do you think is killing it right now? :upside_down...
New
AstonJ
I have seen the keycaps I want - they are due for a group-buy this week but won’t be delivered until October next year!!! :rofl: The Ser...
New
AstonJ
In case anyone else is wondering why Ruby 3 doesn’t show when you do asdf list-all ruby :man_facepalming: do this first: asdf plugin-upd...
New
wmnnd
Here’s the story how one of the world’s first production deployments of LiveView came to be - and how trying to improve it almost caused ...
New
mafinar
This is going to be a long an frequently posted thread. While talking to a friend of mine who has taken data structure and algorithm cou...
New
PragmaticBookshelf
Author Spotlight: Sophie DeBenedetto @SophieDeBenedetto The days of the traditional request-response web application are long gone, b...
New
AstonJ
Curious what kind of results others are getting, I think actually prefer the 7B model to the 32B model, not only is it faster but the qua...
New

Sub Categories: