I have this list of strings and some prefixes. I want to remove all the strings from the list that start with any of these prefixes. I tried:
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list:
list.remove(word.startswith(prexixes)
So I want my new list to be:
list = ['hi', 'holla']
but I get this error:
ValueError: list.remove(x): x not in list
What's going wrong?
Greg's solution is definitely more Pythonic, but in your original code, you perhaps meant something like this. Observe that we make a copy (using list[:]
syntax) and iterate over the copy, because you should not modify a list while iterating over it.
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list[:]:
if word.startswith(prefixes):
list.remove(word)
print list