-2

I want to create a list with unique elements, and a set seems like the best way to do it. However, I get "unhashable type: 'list'" error, because apparently, you can't put lists into a set. I really don't want to convert all of my lists into strings, and add that to a list, then make it a set. For example, I want to add all of these to a list, and make that a set, getting rid of b.

a = [1,2,3]
b = [1,2,3]
c = [2,4,6]

I want to be able to get elements from the set, and elements from the list too, but have unique elements.

Ryan Fu
  • 21
  • 4
  • 2
    If the elements are hashable you can convert them to tuples, and the convert them back to list – Dani Mesejo Dec 25 '20 at 09:15
  • 1
    You can use a FrozenSet instead. – Tarik Dec 25 '20 at 09:16
  • 1
    @Tarik That just freezes the set, it doesn’t make the lists hashable. – deceze Dec 25 '20 at 09:17
  • 2
    OP can you better explain what you want to achieve. Put more code including what is failing. – Tarik Dec 25 '20 at 09:18
  • 2
    Does this answer your question? [Add list to set?](https://stackoverflow.com/questions/1306631/add-list-to-set) – Abhigyan Jaiswal Dec 25 '20 at 09:25
  • 1
    I had a similar problem before. The solution with tuples is problematic since tuples preserve the order of elements and hence lists `[1,2,3]` and `[1,3,2]` would be registered as different entities even though all the elements inside of them are not unique. Perhaps a better solution is to use a set of frozensets: `set([frozenset(a), frozenset(b), frozenset(c)])` There, `a` and `b` sequence duplicates are filtered out even if their unique elements were in different order. – Dr__Soul Dec 25 '20 at 09:45

1 Answers1

4

You can convert list to tuple and then put it into the set.

>>> l = [[1, 2, 3], [2, 4, 6], [1, 2, 3], [2, 4, 6]]
>>> set(tuple(i) for i in l)
{(1, 2, 3), (2, 4, 5)}
Aarsh
  • 130
  • 1
  • 9