Reputation: 3216
I'm trying to run a program which is effectively doing the following:
if [4, 5, False, False, False, False] in {}
And, on this line, I'm getting a TypeError: unhashable type 'list'
What am I doing wrong?
Upvotes: 1
Views: 7139
Reputation: 26435
The code if foo in {}
checks if any of the keys of the dictionary is equal to foo
.
In your example, foo
is a list. A list is an unhashable type, and cannot be the key of a dictionary.
If you want to check if any entry of a list is contained in a dictionaries' keys or in a set, you can try:
if any([x in {} for x in (4, 5, False)])
.
If you want to check if any of your values is equal to your list, you can try:
if any([v == [4, 5, False, False, False, False] for v in your_dict.values()])
Upvotes: 5
Reputation: 1867
A set
holds hashable objects, which means that they are sortable and it enables efficient search/insert method.
On the other hand a list
is not hashable. That's why your code makes error.
I recommend to use tuple
instead of list
.
if (4, 5, False, False, False, False) in {}:
...
Upvotes: 1
Reputation: 7180
You can do something like
if all(x in {} for x in [4, 5, False, False, False, False]):
....
or
if any(x in {} for x in [4, 5, False, False, False, False]):
....
depending on what you want
Upvotes: 0