I am trying to filter out a list using another list. However, the elements of the list I am using to filter the other list is not identical strings. Please see my example as it will make more sense:
mylist = ['14001IB_L1P0', '14001OB_L1P1', '14002IB_L3P0', '14003OB_L1P1', '14001OB_L2P0']
remove_list = ['14001', '14002']
I want to remove the values from mylist that start with the values from remove_list. I have tried doing this:
filtered_mylist = mylist[:]
for x in remove_list:
for i in filtered_mylist:
if x in i:
print('remove ' +i)
filtered_mylist.remove(i)
else:
print('keep '+i)
However, this is the result:
remove 14001IB_L1P0
keep 14002IB_L3P0
keep 14003OB_L1P1
remove 14001OB_L2P0
keep 14001OB_L1P1
remove 14002IB_L3P0
and this is what filtered_mylist consists of:
['14001OB_L1P1', '14003OB_L1P1']
However, it should consist of only 1 element:
['14003OB_L1P1']
It seems to me that for some reason, the loop has skipped over '14001OB_L1P1', the second element in the first loop. Why has this happened?