0

I have the following list:

['10.10.10.10', '20.20.20.20', '30.30.30.30', '10.20.30.40|locationInherited=true', '40.40.40.40', '8.8.8.8|locationInherited=true']

I need to remove all elements that contain '|locationInherited=true', so both '10.20.30.40|locationInherited=true' & '8.8.8.8|locationInherited=true' need to be removed so all that is left in the list is ['10.10.10.10', '20.20.20.20', '30.30.30.30', '40.40.40.40']

I have tried

for elem in list:
    if '|locationInherited=true' in elem:
        list.remove(elem)

And

while list.count('|locationInherited=true') > 0:
            list.remove('|locationInherited=true')

Neither produce an error but neither remove all the necessary elements.

I.T. Guy
  • 111
  • 1
  • 10
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – Davy M Sep 15 '17 at 00:38
  • A list comprehension with `if '|locationInherited=true' not in elem` being the case for which elements get copied into the new list might be the way to go – Davy M Sep 15 '17 at 00:38
  • 2
    You shouldn't remove from a list while iterating over it. You could build up a new list, but this is what list comprehensions were made for: `l = [e for e in list if '|locationInherited=true' not in e]`. – Christian Dean Sep 15 '17 at 00:39

1 Answers1

1

Try this:

import re
ips = ['10.10.10.10', '20.20.20.20', '30.30.30.30',
       '10.20.30.40|locationInherited=true', '40.40.40.40', '8.8.8.8|locationInherited=true']

for i in ips:
    if re.search('.*\|locationInherited=true', i):
        ips.pop(ips.index(i))

output:

['10.10.10.10', '20.20.20.20', '30.30.30.30', '40.40.40.40']

Using module re, you can easily find a substring inside a string.

See the docs

Abe
  • 1,357
  • 13
  • 31