-1

I am trying to iterate through a list of strings and remove any which contain an open parentheses.

'''

counter = 0
for i in self.command_list:
            if i.find("(") != -1:
                self.command_list.pop(counter)
            counter = counter + 1

'''

The if statement properly identifies if a string contains an open parentheses so why isn't pop working?

sabertenn
  • 31
  • 4
  • `[i for i in self.command_list if "(" not in i]` - and very bad idea to mutate a list while iterating over it. – luk2302 Aug 11 '23 at 10:22
  • Related question about why it is a bad idea to remove items from a list that you are iterating over: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it-in-python – Pux Aug 11 '23 at 10:27

2 Answers2

0

BTW, initialisation of counter is missing.

After the first pop(), the list was already changed, so your counter is wrong by 1. This gets worse by each pop() you do.

You get an excellent link and a suggestion in the comments. The comments say, it is bad idea to change a list when you are iterating over it. Using pop many times is not efficient. If you insist on that, I would be updating counter only in the else: part of the if statement. There is also a suggestion going through the list backwards.

Better is to use the construct from the comment:

[ i for i in self.command_list if "(" not in i ]

minorChaos
  • 101
  • 7
0
command_list = ["first",
                "fir(st",
                "second",
                "(second)"]

command_list = [i for i in command_list if "(" not in i]
print(command_list)

The problem might be that you are looping through the command_list and when you pop, indexing changes on-the-fly, so you miss adjacent items.

If you don't need to store popped items you can re-write the list as above.

pansiano
  • 46
  • 3