2

If you have a list of sets like this:

a_list = [{'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'c', 'b'}, {'a', 'c', 'b'}]

How could one get the number of unique sets in the list?

I have tried:

len(set(a_list ))

I am getting the error:

TypeError: unhashable type: 'set'

Desired output in this case is: 3 as there are three unique sets in the list.

naive
  • 367
  • 1
  • 3
  • 9

2 Answers2

1

You can use a tuple:

a_list = [{'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'c', 'b'}, {'a', 'c', 'b'}]
result = list(map(set, set(map(tuple, a_list))))
print(len(result))

Output:

[{'a', 'b'}, {'a'}, {'c', 'a', 'b'}]
3

A less functional approach, perhaps a bit more readable:

result = [set(c) for c in set([tuple(i) for i in a_list])]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

How about Converting to a tuple:

a_list = [{'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'c', 'b'}, {'a', 'c', 'b'}]

print(len(set(map(tuple, a_list))))

OUTPUT:

3
DirtyBit
  • 16,613
  • 4
  • 34
  • 55