1

I have a list of lists of tuples:

x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]

I want all the unique lists present in the list x

My output should be:

x=[[(0,0),(0,1)],[(1,2),(2,3)]]

I tried using x=list(set(x)) but it gives error: 'list is not hashable', I also tried using numpy.unique but it does not give desired output. How can I implement this?

Cute Panda
  • 1,468
  • 1
  • 6
  • 11

2 Answers2

2

list as mutable and hence can not be used as an element to a set. However, you can type-cast the list to tuple which are immutable, and then you can get unique elements using set. Here I am using map() to covert all sub-lists to tuple:

>>> x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]

>>> set(map(tuple, x))
{((1, 2), (2, 3)), ((0, 0), (0, 1))}

To type-cast the set back to list and change back nested tuple to list, you can further use map() as:

>>> list(map(list, set(map(tuple, x))))
[[(1, 2), (2, 3)], [(0, 0), (0, 1)]]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

i would do something like this:

x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]

result = []
for i in x:
   if not i in result:
      result.append(i)

print(result)

maybe it is not the fastest way but certainly it is the simpler.
Otherwise you can use the most "cool" way, you can use sets. Sets are like lists that don't allow equal elements.

x = x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]
result = list(map(list,set(map(tuple,x))))
Giuppox
  • 1,393
  • 9
  • 35
  • @MalayParmar if this is how you managed to solve the problem remember to accept the answer by clicking the accept sign, so to help other users if they came across the same problem. – Giuppox Feb 12 '21 at 09:24