0

I need to reduce the size of a list iteratively based on an equivalence condition. The idea is that I iterate in the list and, for each element, I eliminate all the elements of the list related (equivalent) to that element.

For example, consider that G is a list of tuples. I want to eliminate all tuples that can be obtained as a permutation of another tuple already in the list. Let equiv(g) be the function that returns a list of all permutations of g (excluding g itself).

I tried this code:

for g in G:
    for gg in equiv(g):
        if gg in GN:
            G.remove(gg)

This should leave in the list only one element for each equivalence class. However, it doesn't seem to work properly. I suspect I am doing it the wrong way.

Note that I cannot iterate over a copy of the list G, as suggested for example here, because in this way all elements of each class of equivalence would be removed. In other words, I don't want to remove based on elements what have already been removed.

Massimo2013
  • 533
  • 4
  • 17
  • 1
    Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – JonSG Mar 14 '22 at 16:40
  • Is the order of the list important? You need to remove equivalents of the first elements in the list first? – Stuart Mar 14 '22 at 16:57

1 Answers1

3

For loop iterate through the list by incrementing the indexes, which will have problems if you delete elements and refreshes the index. Try to use while loop + pop

new_G = []
while len(G) > 0: # while G: 
    g = G.pop(0)
    for gg in equiv(g):
        G.remove(gg)
    new_G.append(g)
Yingxu He
  • 130
  • 1
  • 6