Home > OS >  Remove related element from list while iterating in python
Remove related element from list while iterating in python

Time:03-15

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.

CodePudding user response:

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:
    g = G.pop(0)
    for gg in equiv(g):
        G.remove(gg)
    new_G.append(g)
  • Related