I am trying to get a list of list of tuples : something like [ [(1,0),(2,0),(3,0)],[(1,1),(2,1),(3,1)....]]
I used this statement
set([(a,b)for a in range(3)]for b in range(3))
But it gives me an error
TypeError: unhashable type: 'list'
I have 2 questions for the Python Guru's:
a) When I look at the Python definition of Hashable -
"An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method)"
when I used dir function on the expression above
dir([(a,b)for a in range(3)]for b in range(3))
it seems to say the __hash__
is there. So, why do I get the error?
I was able to get [[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
by using the list command :
list(list((a,b) for a in range(3)) for bin range(3))
b)list and set both takes Iterable as parameter. How come one works(list) and another doesn't (set)?
The Python "TypeError: unhashable type: 'list'" occurs when we use a list as a key in a dictionary or an element in a set. To solve the error, convert the list to a tuple, e.g. tuple(my_list) as list objects are mutable and unhashable.
The “TypeError: unhashable type: 'list'” error is raised when you try to assign a list as a key in a dictionary. To solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary. Now you're ready to solve this error like a professional coder!
Slice is not a hashable object, and therefore it cannot be used as a key to a dictionary. To solve this error, specify the appropriate key names for the values you want or use an iterable object like items() and iterate over the items in the dictionary.
The Python "TypeError: unhashable type: 'set'" occurs when we use a set as a key in a dictionary or an element in another set . To solve the error, use a frozenset instead, because set objects are mutable and unhashable.
You are creating a set
via set(...)
call, and set
needs hashable items. You can't have set of lists. Because list's arent hashable.
[[(a,b) for a in range(3)] for b in range(3)]
is a list. It's not a hashable type. The __hash__
you saw in dir(...) isn't a method, it's just None.
A list comprehension returns a list, you don't need to explicitly use list there, just use:
>>> [[(a,b) for a in range(3)] for b in range(3)] [[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
Try those:
>>> a = {1, 2, 3} >>> b= [1, 2, 3] >>> type(a) <class 'set'> >>> type(b) <class 'list'> >>> {1, 2, []} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> print([].__hash__) None >>> [[],[],[]] #list of lists [[], [], []] >>> {[], [], []} #set of lists Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With