Sets in Python

Dustan DustanGroups at
Wed Sep 19 03:49:09 CEST 2007

On Sep 18, 7:39 pm, sapsi <saptarshi.g... at> wrote:
> Hello,
> I recently tried using the set function in Python and was surprised to
> find that
> a=[ 1, 2,3, [1,2] ]
> doesn't work with 'set', throwing TyperError (unhashable exception). I
> found out that this is because lists can't be hashed.
> So,this implies 'a' cannot be a set in python which i think is quite
> unfortunate, after all 'a' does look like a mathematical set.

It is not the variable *a* itself that's a problem when constructing a
set (ie. set(a)); it is the content. set() goes through each of the
items and adds that item to the set. 1, 2, and 3 are valid because
they can be hashed. The next item in the list, however, is [1,2], and
cannot be hashed because it is a mutable list.

The solution is as Raymond Hettinger said:

a = set([1, 2, 3, frozenset([1, 2])])

> My question is,
> 1) Why can't lists be hashed?

They're mutable.

> and
> 2) This is not related, but is there i neat way (without pop and list
> comprehension) to convert a set into a list? I say neat because i'm
> guessing using list comprehension might turn out be slow and there
> might be other methods which are faster.


> Thank you for your time

You're welcome.

More information about the Python-list mailing list