I've seen some questions here very related but their answer doesn't work for me. I have a list of lists where some sublists are repeated but their elements may be disordered. For example
g = [[1, 2, 3], [3, 2, 1], [1, 3, 2], [9, 0, 1], [4, 3, 2]]
The output should be, naturally according to my question:
g = [[1,2,3],[9,0,1],[4,3,2]]
I've tried with set
but only removes those lists that are equal (I thought It should work because sets are by definition without order). Other questions i had visited only has examples with lists exactly duplicated or repeated like this: Python : How to remove duplicate lists in a list of list?. For now order of output (for list and sublists) is not a problem.
What about using mentioned by roippi frozenset this way:
If you don't care about the order for lists and sublists (and all items in sublists are unique):
If a sublist may have duplicates e.g.,
[1, 2, 1, 3]
then you could usetuple(sorted(sublist))
instead offrozenset(sublist)
that removes duplicates from a sublist.If you want to preserve the order of sublists:
Example:
See In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order?
(ab)using side-effects version of a list comp:
For those (unlike myself) who don't like using side-effects in this manner:
The reason that you add
frozenset
s to the set is that you can only add hashable objects to aset
, and vanillaset
s are not hashable.I would convert each element in the list to a frozenset (which is hashable), then create a set out of it to remove duplicates:
If you need to convert the elements back to lists: