Anna
Anna

Reputation: 23

How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?

    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?

Upvotes: 0

Views: 1577

Answers (3)

user2390182
user2390182

Reputation: 73480

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

Upvotes: 2

Khanh Nghiem
Khanh Nghiem

Reputation: 29

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

Upvotes: 0

alexisdevarennes
alexisdevarennes

Reputation: 5642

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)

Upvotes: 0

Related Questions