3

I have a list of lists, and I want to turn it into a set of lists, in order to compare it with other sets.

For example, I want to do:

mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
myset = set(mylist)
myset

And get:

{[1, 2, 3], [4, 5, 6], [7, 8, 9]}

But this error pops up:

Traceback (most recent call last):
  File "A:/Users/.../Testfile.py", line 2, in <module>
    myset = set(mylist)
TypeError: unhashable type: 'list'

I also tried this, a solution posted at https://stackoverflow.com/questions/30773911/:

myset = set(x for lst in mylist for x in lst)
print(myset)

But this merges all of the internal lists.

{1, 2, 3, 4, 5, 6, 7, 8, 9}

Is there a way to convert mylist into a set of lists?

LogicalX
  • 95
  • 1
  • 10
  • 1
    @Hari The problem with that is that it only works with lists of hashable items, and a list isn't hashable, as the error message points out. – LogicalX Sep 03 '19 at 00:45

2 Answers2

5

lists are not hashable in python. Instead, map to tuples, which are hashable:

>>> mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> set(map(tuple, mylist))
{(4, 5, 6), (7, 8, 9), (1, 2, 3)}
>>> set(tuple(x) for x in mylist)
{(4, 5, 6), (7, 8, 9), (1, 2, 3)}

You can also use a clean set comprehension here as well:

>>> {tuple(x) for x in mylist}
{(4, 5, 6), (7, 8, 9), (1, 2, 3)}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
3

Would you be confortable turning your arrays into tuples?

mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
myset = set()

for array in mylist:
  myset.add(tuple(array))

print(myset)

This gives you: {(4, 5, 6), (7, 8, 9), (1, 2, 3)}

Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35