Search code examples
pythonpython-3.xlistunique

How to get unique values in square brackets from list


I have a list with this type of values:

my_list = [(1,2), (3,4), (5,6), (3,4), (2,1)]

I want to get only unique values from there. I also consider (1,2) and (2,1) as same. So desired result is:

[(1,2), (3,4), (5,6)]

How to do it?


Solution

  • Pretty ugly, but here's one solution.

    >>> list(set(tuple(set(x)) for x in my_list))
    [(1, 2), (3, 4), (5, 6)]
    

    Converts each tuple to a set, then back to a tuple, collected in an outer set to get rid of dupes, then cast back to list.