Is it possible to delete all items in a list that don’t contain a regular expression string?
I was thinking of maybe returning only a regular expression string, and if there wasn’t one, making the list item empty, and then iterating over the list a second time to delete all the empty entries, but that seems inefficient.
Any thoughts?
For example, lets say I have:
["cat", "dog", "monkey", "Fred", "sad"]
and I write a regex that only selects for sad. I want all of the others to be (preferably) deleted.
The easiest way to do this is to construct a new list using a list comprehension:
or, using
filter():