How to remove a string from a list that startswith prefix in python

EerlijkeDame picture EerlijkeDame · May 1, 2014 · Viewed 22k times · Source

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?

Answer

Greg Hewgill picture Greg Hewgill · May 1, 2014

You can create a new list that contains all the words that do not start with one of your prefixes:

newlist = [x for x in list if not x.startswith(prefixes)]

The reason your code does not work is that the startswith method returns a boolean, and you're asking to remove that boolean from your list (but your list contains strings, not booleans).

Note that it is usually not a good idea to name a variable list, since this is already the name of the predefined list type.