Remove 2 duplicated swap sublists in list

Question:

I have a two-dimensional list like this:

[[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]]

I want to remove all the sublists that are duplicates but in reverse order (ie: [1, 6] and [6, 1], [3, 7] and [7, 3]).

The result should be:

[[1, 6], [2, 5], [3, 7], [8, 9]]
Asked By: Beam291

||

Answers:

You can use set and frozenset:

lst = [[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]]

output = set(map(frozenset, lst))

print(output)
# {frozenset({1, 6}), frozenset({2, 5}), frozenset({3, 7}), frozenset({8, 9})}

If you want to have a list of lists, then you can append the following:

output = list(map(list, output))
print(output)
# [[1, 6], [2, 5], [3, 7], [8, 9]]
Answered By: j1-lee

You can do this easily by checking if the sorted list is already had already been added. Like this:

data = [[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]]
new_data = []
for lst in data:
    if sorted(lst) not in new_data:
        new_data.append(lst)
print(new_data)  # => [[1, 6], [2, 5], [3, 7], [8, 9]]

This works because [1, 6] and [6, 1] return the same sorted list.

Answered By: Michael M.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.