vlad vlad - 5 months ago 31
Python Question

Unique items in list of sets

If I have list of sets:

>>> lst = [{1, 2}, {0, 1}, {1, 2}]

How to return unique items?

Trying well known
does not work:

>>> set(lst)
TypeError: unhashable type: 'set'


If by "unique items" you mean unique sets, you could just use frozenset, which is a hashable but immutable version of set. You could either build your sets as frozenset objects initially, or if you need to mutate them, do something like:

uniques = set(frozenset(s) for s in lst)


>>> uniques
set([frozenset([1, 2]), frozenset([0, 1])])