0
    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x) 

    print(check)

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

Anna
  • 23
  • 3

3 Answers3

2

Repeated removal from a list is never a good a idea since it is O(N). You can do the cleaning in one non-nested run-through, however. It is better to build a clean list from scratch and possibly reassign it to the same variable:

seen, no_dupes = set(), []
for c in check:
    s = tuple(sorted(c))
    if s not in seen:
         seen.add(s)
         no_dupes.append(c)
# check[:] = no_dupes  # if you must
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • I tried to implement the code in my function but get this error: "unhashable type: 'list' " . Have I perhaps implemented it wrong? – Anna Nov 15 '17 at 20:52
0

Use in and not ==

for x in check:
    this = sorted(x) #the first tuple
    for y in check:
        that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
        if this in that:
            check.remove(x) 
     # alternatively you might need to loop through this if its a tuple of tuples
     # for t in this:
     #     if t in that:
     #         check.remove(x)

print(check)
alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38
0

Consider the instance [(1,1), (1,1), (1,1)] In the first iteration, x is assigned to the first element in the list, y is also assigned to the first element, since x=y, remove x. Now when y is iterated to the second element, x=y, but now x has already been removed in the previous iteration. You should use dynamic programming:

new_check = []
for x in check:
   this = sorted(x)
   if x not in new_check:
      new_check.append(x)
return new_check
  • 1
    It works for the first list in the list 'check', but it doesn't show the rest of the lists. Perhaps because of the return? as the for loop then stops (so it's only for the first list in the list 'check')? – Anna Nov 15 '17 at 20:58
  • Yes, take out the return – Khanh Nghiem Nov 15 '17 at 21:16