Bob Smeldyn
Bob Smeldyn

Reputation: 46

Why can't I make a frozeset of a list?

When I try the code below:

frozenset([[]])

I get

Traceback (most recent call last):
   File "-----.-----.py", line 1, in <module>
    frozenset([[]]) TypeError: unhashable type: 'list'

Why can't I do this?

Upvotes: 0

Views: 165

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

Because lists are mutable and their values can change.

You need immutable objects like strings or tuples etc.

If the value of an object changes it's hash value would also change.

object values and types

Brandon Rhodes gives a very good explanation on how hashing works in Python in relation to dictionaries the mighty dictionary

Upvotes: 1

s16h
s16h

Reputation: 4855

In Python, the elements of set must be hashable. As the Python docs explain:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() method). Hashable objects which compare equal must have the same hash value.

This is because the set needs to be able to efficiently perform set operations and quickly determine if an item is in the set or not (by comparing hash values). Since list are mutable and not hashable, then they can't be put in a set.

In your code, if you were to say frozenset([]) then that would be fine. In this case, you are creating a frozenset of the items in [] which should all be hashable (since there aren't any items in the list, then the hashable-ness is not a problem). But when you say frozenset([[]]), then Python tries to create a frozenset of all the items in the outer list; but the first item in the outer list is another list ([]) which is not hashable; so you will get an error.

Upvotes: 4

Related Questions