EerlijkeDame
EerlijkeDame

Reputation: 507

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

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?

Upvotes: 18

Views: 37715

Answers (3)

David J Merritt
David J Merritt

Reputation: 189

print len([i for i in os.listdir('/path/to/files') if not i.startswith(('.','~','#'))])

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993045

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.

Upvotes: 37

merlin2011
merlin2011

Reputation: 75555

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

Upvotes: 10

Related Questions