I am trying to remove all elements of a list that do not match a given regular expression. I am using the following code:
import json
import re
skus = [u'12', u'344', u'56', u'PSJAI12345', u'57']
pattern = re.compile('([A-Z]{5})(\d{5})')
for sku in skus:
if pattern.match(sku):
print("skip")
else:
skus.remove(sku)
print json.dumps(skus)
The output is:
["344", "PSJAI12345"]
the expected output was:
["PSJAI12345"]
It seems like items with odd index are somehow skipping iteration (skip
not getting printed when PSJAI12345
matched the regular expression). I can't understand why. Please can someone explain what's going on here.