comparing all values of a list to regex

Alex Martelli aleax at
Thu Sep 26 15:55:58 CEST 2002

Delaney, Timothy wrote:
>> num_matches = [ there.match(item) is not None for item in
>> alist ].count(1)
> # Expanded out for clarity - could be one line
> matches = map(regexp.match, alist)
> matches = filter(None, matches)
> matches = len(matches)

The list-comprehension equivalent of this would be:

matches = len([ item for item in alist if there.match(item) ])

and may indeed be clearer than the .count approach I originally
proposed (except that I think that naming the variable matches
is ambiguous -- num_matches or numMatches & being preferable).

A more concise expression of your approach would of course be:

matches = len(filter(there.match, alist))

I don't see exactly what value the call to map adds in your case.

> # Find out which list to append to
> match_list = match_all
> if not matches:
>     match_list = match_none
> elif matches == 1:
>     match_list = match_one
> elif matches != len(alist):
>     match_list = match_some
> match_list.append(alist)

Yes, choosing a list first and then appending to the chosen
list is nicer, but you cannot do that within the original
specs (for all I know the match_some list might grow
unbearably large over time, in this case).

> Note that I added an additional case - where more than one matched, but
> not all.

Yep, that's the part that's out of the original specs.

The concise equivalent alternative here might be (e.g.):

{0:match_none, 1:match_one, len(alist):match_all}.get(
    matches, match_some).append(alist)

or to get back in the original specs:

match_list = {0:match_none, 1:match_one, len(alist):match_all}.get(matches)
if match_list is not None: match_list.append(alist)


More information about the Python-list mailing list