Bug-creating a set of tuples with a list in them

_
_ginevra_ (620 points)
0 10 15
asked Dec 13, 2020 in HW8 required by _ginevra_ (620 points)
Hi!

When I try to create a set with tuples that have a list in the first element I get type error: unhashable type:list.

for example:

list_of=[(['vendita','diamanti','rubati'],'MILANO'), (['mata','hari','ha'],'CANCUN')]

set_of=set(list_of)

this happens also when I add the tuples to the set directly one at a time

Do you know why this happens? Do you have any other ways through which I can create a set of these tuples?

Would really appreciate any suggestions. Thank you.
79 views

1 Answer

Best answer
B
Bruni1933963 (1160 points)
0 0 4
answered Dec 13, 2020 by Bruni1933963 (1,160 points)
selected Dec 13, 2020 by _ginevra_

Hi Ginevra,

Sets require their items to be hashable. In Python only the immutable ones, such as strings, numbers, and tuples, are hashable. While lists and dictionaries are not hashable. 

But notice that when you pass the set() an iterable, it builds a set out of the elements provided in the iterable. So when you pass set() a list, it creates a set containing the objects within the list, but if you pass a list of lists it's not going to work as you expect because it cannot build a set out of the elment list.

This is why Python complains in your case:

         - you're trying to set a tuple (fine) but this tuple contains lists !

         - also when you try to set the hole list_of is not the outer list to complain but the small ones inside of the tuples.

I'm pretty sure I didn't get your idea and why you need those tuples so maybe this is not gonna work for you but notice that Python wouldn't complain to set a tuple of strings.. so set(('vendita','diamanti','rubati','MILANO')) is going to work and even set([('vendita','diamanti','rubati','MILANO'), ('mata','hari','ha','CANCUN')]) will work.

Hope this helps :)

_
_ginevra_ (620 points)
0 10 15
commented Dec 13, 2020 by _ginevra_ (620 points)
edited Dec 13, 2020 by _ginevra_
Ok yes I understand thank you! I just thought for some strange reason that the secret had to be in the form of a list, not a string. I just wasted hours on literally nothing. :)