-3

I'm having a fairly weird problem and maybe I'm missing something basic. I have a large list of tuples. Each tuple has between 0-7 numbers in it. I want to remove all tuples from the list that have less than 3 or greater than 5 numbers.

Here's an example of the first few elements of the list: my_list = [(), (1,), (3,), (4,), (5,), (6,), (7,), (8,), (1, 3), (1, 4), (1, 5), etc....] It is 128 items long. The script I wrote is:

for n in my_list:
    if len(n) < 3 or len(n) > 5:
        my_list.remove(n)

This code removes SOME of the elements of the list that meet the criteria, but not all. Interestingly, if I copy paste the same code above multiple times, it removes a few more elements each time. Running it once cuts the list from 128 to 109. Running it a second time cuts it to 100. A third time cuts it to 92...I don't understand what is happening at all. Can someone explain it to me? Thanks!

  • 2
    Don't modify the list you're iterating over; instead iterate over a copy or store the items to remove until after the iteration has completed. – MatsLindh May 11 '22 at 22:05

0 Answers0