Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing a set from a list if found

I have the following code, where it acts strange:

teamed = [{1, 2}, {3, 4}, {5, 6}, {8, 7}, {9, 10}, {11, 12}, {1, 3}, {2, 4}, {5, 7}, {8, 6}, {9, 13}, {10, 14}]
game_3 = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14]
combi = [set(combo) for combo in itertools.combinations(game_3, 2)]
for c in combi:
    if c in teamed:
        combi.remove(c)
        
print(combi)

I wanted to remove any occurrences of any set that is in teamed from combi, but strangely {1,3} was not removed and when i tried to use ‘print(c)’ after the for loop i found out it doesn`t loop over ‘{1,3}’.

The result I get is like this, however {1,3} is already in teamed, and it was not removed from combi:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {8, 1}, {1, 11}, {1, 12}, {1, 13}, {1, 14}, {2, 3}, {2, 5}, {2, 6}, {2, 7}, {8, 2}, {2, 11}, {2, 12}, {2, 13}, {2, 14}, {3, 5}, {3, 6}, {3, 7}, {8, 3}, {11, 3}, {3, 12}, {3, 13}, {3, 14}, {4, 5}, {4, 6}, {4, 7}, {8, 4}, {11, 4}, {4, 12}, {4, 13}, {4, 14}, {5, 7}, {8, 5}, {11, 5}, {12, 5}, {13, 5}, {5, 14}, {6, 7}, {11, 6}, {12, 6}, {13, 6}, {6, 14}, {11, 7}, {12, 7}, {13, 7}, {14, 7}, {8, 11}, {8, 12}, {8, 13}, {8, 14}, {11, 13}, {11, 14}, {12, 13}, {12, 14}, {13, 14}]

>Solution :

As people have eluded in the comments, editing a list that you are actively looping over can create problems, a simple solution is to append all values not in ‘teamed’ to a new list, for example:

import itertools

new_list = []

teamed = [{1, 2}, {3, 4}, {5, 6}, {8, 7}, {9, 10}, {11, 12}, {1, 3}, {2, 4}, {5, 7}, {8, 6}, {9, 13}, {10, 14}]
game_3 = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14]
combi = [set(combo) for combo in itertools.combinations(game_3, 2)]
for c in combi:
    if c not in teamed:
        new_list.append(c)

print(new_list)

Let me know if this achieves what you’re aiming for.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading