Python: Searching for a string within a list – List comprehension

The simple way to search for a string in a list is just to use ‘if string in list’. eg:

But what if you need to search for just ‘cat’ or some other regular expression and return a list of the list items that match, or a list of selected parts of list items that match.
Then you need list comprehension.

Lets work through that. Firstly we’re going to use the regular expression library so we import that. re.compile lets us create a regular expression that we can later use for search and matching.

Now lets look at a simpler comprehension line:

This is creating a list of the results of running regex.search() on each item in l.

Next we want to exclude the None values. So we use an if statement to only include the not None values:

Lastly rather than returning just a list of the m’s, which are RE match objects, we get the information we want from them.

Very useful if you have say a list of Solaris 11 package fmri’s and want to extract a set of package names based on a regular expression of their version number for instance 🙂

4 thoughts on “Python: Searching for a string within a list – List comprehension”

  1. Another option: use filter() function

    x=re.comple(‘regular_string’)
    sub_list = filter(x.match, string_list)

Leave a Reply

Your email address will not be published. Required fields are marked *