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?
Given the list [‘a’,’ab’,’abc’,’bac’] , I want to compute a list with strings that
Share
This simple filtering can be achieved in many ways with Python. The best approach is to use “list comprehensions” as follows:
Another way is to use the
filterfunction. In Python 2:In Python 3, it returns an iterator instead of a list, but you can cast it:
Though it’s better practice to use a comprehension.