1

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?

2
  • What exactly are you trying to achieve? Commented Feb 7, 2013 at 14:37
  • I have data structures that look something along the lines of [4,5,False,False,False,False] and I want to find them within an unordered list of items. {} was an example (that my code happened to be failing on at the time) of such a thing. I'm now using a list instead of a dictionary, and it's working out better. Commented Feb 7, 2013 at 15:13

3 Answers 3

5

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()])

Sign up to request clarification or add additional context in comments.

Comments

1

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 {}:
  ...

2 Comments

This is still more efficiently written as if False:. It would be more useful if the OP told us what s/he really wants to achieve.
Thanks for noticing that tuples can be used as dictionary keys instead of lists.
0

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

3 Comments

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]]).
@gerrit any(x in {} for x in [4, 5, False]) returns False for me, both in Python 2.7 and 3.3
@JanneKarila Aah! I was using pylab, which does from numpy import *. numpys any is shadowing the builtin any.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.