Remove elements from a list based on a condition in Python, problem: loop removes only the first instance

Question:

For each element in my list I’d like to check:

  • if it includes ‘strategies available for player’, or
  • is it equal to ‘n’

If yes, the element should be removed.

I’ve written a loop to iterate over the list. It removes the first instance of ‘strategies availbale for player’ just fine but totally ignores the second one. I have no idea why. What am I missing?

I can handle it some other way but I would like to understand what is happening here.

a_list = ['-2 strategies available for player-n',
 'd1 = c(0.0216,0.0519,0.0714,0.0942,0.1050);n',
 'd2 = c(0.0382,0.0475,0.0526,0.0768,0.1173);n',
 'd3 = c(0.0297,0.0561,0.0822,0.0834,0.1321);n',
 'd4 = c(0.1179,0.1233,0.1351,0.1369,0.1669);n',
 'd5 = c(0.0143,0.0256,0.0294,0.0366,0.0461);n',
 'd6 = c(0.03300,0.0535,0.0832,0.0867,0.1014);n',
 'd7 = c(0.0661,0.0921,0.1205,0.1398,0.1650);n',
 'd8 = c(0.0629,0.08316,0.1210,0.1467,0.1642);n',
 'n',
 '-3 strategies available for player-n',
 'd1 = c(0.0594,0.0691,0.0797,0.1020,0.1134);n',
 'd2 = c(0.0613,0.0737,0.1075,0.1160,0.1299);n',
 'd3 = c(0.1082,0.1216,0.1343,0.1410,0.1495);n',
 'd4 = c(0.0949,0.1086,0.1288,0.1506,0.1583);n',
 'd5 = c(0.0371,0.0498,0.0571,0.0688,0.0961);n',
 'd6 = c(0.0752,0.0962,0.1056,0.1218,0.1465);n',
 'd7 = c(0.0849,0.1209,0.1321,0.1574,0.1663);n',
 'd8 = c(0.0737,0.1216,0.1498,0.1793,0.1923);']

for el in a_list:
    if 'strategies available for' in el or el == 'n':
        a_list.remove(el)

for el in a_list:
    print(el)
Asked By: jarsonX

||

Answers:

I would suggest to create another list using list comprehension and applying conditions accordingly:

el = [x for x in a_list if not 'strategies available for' in x or x != 'n']

But, if you wish to remove the elements from the current list and without creating a new one, you SHOULD iterate from the end whenever you are trying to remove elements while in a loop. This does not mess up the indexing.

for el in a_list[::-1]:
    if 'strategies available for' in el or el == 'n':
        a_list.remove(el)
Answered By: Sam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.