Fix Python – Filtering a list of strings based on contents


Asked By – Chris.Jie

Given the list ['a','ab','abc','bac'], I want to compute a list with strings that have 'ab' in them. I.e. the result is ['ab','abc']. How can this be done in Python?

Now we will see solution for issue: Filtering a list of strings based on contents


This simple filtering can be achieved in many ways with Python. The best approach is to use “list comprehensions” as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it’s better practice to use a comprehension.

This question is answered By – Eli Bendersky

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0