How to remove a line from a list starting with a prefix in python

I have a list of strings and some prefixes. I want to remove all lines 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 will go wrong?

+6
source share
3 answers

Greg's solution is definitely more than Pythonic, but in your source code you might have something in mind. Observe that we make a copy (using the list[:] syntax) and iterate over the copy, because you should not modify the 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 
+5
source

You can create a new list containing all words that do not begin with one of your prefixes:

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

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

Please note that it is usually not recommended to specify the list variable, since this is already the name of a predefined type list .

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

All Articles