Search code examples
pythonpython-2.7unique

How to get unique combination value from list of list in python


I have a list of lists like

items = [[1, 2], [2, 3], [2, 1], [1, 2]]

Need to extract only unique combination from the set, no repetition. For example [1,2] and [2,1] are same. In this case, we have to consider only one set.

Expected output: [[1,2],[2,3]]

How to achieve this using python ?


Solution

  • The minimum code to get what you want is like this. If you must have the results as a list of lists, you’ll need a wrapper

    set(frozenset(i) for i in items)
    

    Or if it is not guaranteed that every item in the lists is unique in that list,

    set(tuple(sorted(i)) for i in items)