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?
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?
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()])
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 {}:
...
if False:. It would be more useful if the OP told us what s/he really wants to achieve.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
any(x in {} for x in [4, 5, False]) returns True. I was surprised by this, I guess any considers the iterable as a whole, and an iterator is true. So it should be any([x in {} for x in [4, 5, False]]).any(x in {} for x in [4, 5, False]) returns False for me, both in Python 2.7 and 3.3pylab, which does from numpy import *. numpys any is shadowing the builtin any.