Search code examples
pythonlistdistinct-values

Removing duplicate equivalence classes from a list


I am looking for a way to take a list of elements, some of which may be "equivalent", and return a list with no equivalent elements. My rough attempt is this:

unique = []
for item1 in mylist:
    include = 1
    for item2 in unique:
      if are_these_equivalent(item1, item2):
        include = 0
        break        #no need to examine anymore items
    if include == 1:
      unique.append(item1)

I would guess that algorithmically there's not much to be done, but it feels like the code is a little messy. Are there any nice ways to spruce it up?

EDIT: The equivalence I am using is whether two permutations are conjugate in S_n, but any abstraction of equivalent (in the sense of equivalence classes) should work the same.


Solution

  • In the light of what was said in the comments, here is an improved and corrected version of the code. It is only tangentially better than your original code.

    unique = []
    for item1 in mylist:
      for item2 in unique:
        if are_these_equivalent(item1, item2):
          break
      else:
        unique.append(item1)