What is the best way to delete strings in a string list that that match certain pattern?

Lie Ryan lie.1296 at gmail.com
Fri Nov 6 08:30:18 CET 2009

Peng Yu wrote:
> Suppose I have a list of strings, A. I want to compute the list (call
> it B) of strings that are elements of A but doesn't match a regex. I
> could use a for loop to do so. In a functional language, there is way
> to do so without using the for loop.

In functional language, there is no looping, so that argument is kind of 
pointless. The looping construct in many functional language is a syntax 
sugar for recursion.

In python, instead of explicit loop, you can use either:
   map(pattern.match, list_of_strs)
   [pattern.match(mystr) for mystr in list_of_strs]

or if you want to be wicked evil, you can write a recursive function as 

def multimatcher(list_of_strs, index=0):
     return [] if index >= len(list_of_strs) else (
             list_of_strs[index + 1]

More information about the Python-list mailing list