0

I'm writing a method that takes a list of lists ([[], [], [],], for example), and weeds out all lists that already have an existing permutation in the main list.

For example, if given: [[1, 2, 3, 4], [2, 3, 4, 1], [1, 2, 4, 3]], it would only return [[1, 2, 3, 4]].

Or, if given: [[0, 0, 1, 1], [1, 1, 0, 0], [0, 1, 1, 0], it would only return [0, 0, 1, 1]].

The edge case is if I give it a list like: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ,[0, 0, 0, 0]], it returns [[0, 0, 0, 0], [0, 0, 0, 0]]

This is because the second for loop in my method is ending early, and I can't figure out why. Thanks so much in advance!

def removeDuplicates(self, lists):

    for list in lists:
        list.sort()

    returnList = lists

    for list in lists:
        returnList.remove(list)
        if not list in returnList:
            returnList.append(list)

    return returnList
Kody_06
  • 163
  • 2
  • 9
  • Why not sort the lists, convert them to tuples, run a `set(...)` over the list and then all the duplicates will be gone and you can run `list(...)` over it again if you want to mutate it later? – uspectaculum Oct 29 '17 at 20:09
  • Because you are removing from the list while iterating over it. Note, `returnList = lists` **does not create a copy**. – juanpa.arrivillaga Oct 29 '17 at 20:10

1 Answers1

0

Try this:

def removeDuplicates(lists):
    [list.sort() for list in lists]
    [lists.remove(list) for list in lists[:] if list in lists and len(lists) > 1]
    return lists
gommb
  • 1,121
  • 1
  • 7
  • 21