python - Why can't I make a frozeset of a list? -
when try code below:
frozenset([[]])
i get
traceback (most recent call last): file "-----.-----.py", line 1, in <module> frozenset([[]]) typeerror: unhashable type: 'list'
why can't this?
in python, the elements of set must hashable. python docs explain:
an object hashable if has hash value never changes during lifetime (it needs hash() method), , can compared other objects (it needs eq() method). hashable objects compare equal must have same hash value.
this because set needs able efficiently perform set operations , determine if item in set or not (by comparing hash values). since list mutable , not hashable, can't put in set.
in code, if frozenset([])
fine. in case, creating frozenset
of items in []
should hashable (since there aren't items in list, hashable-ness not problem). when frozenset([[]])
, python tries create frozenset
of items in outer list; first item in outer list list ([]
) not hashable; error.
Comments
Post a Comment