vlad vlad - 3 months ago 13
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
set()
does not work:

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

Answer

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)

Then:

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