Alex Rivera | Logout

What is the most pythonic way to exclude elements of a list that start with a specific character?

Asked 2012-08-03T07:54:51.667
9

I have a list of strings. I want to get a new list that excludes elements starting with '#' while preserving the order. What is the most pythonic way to this? (preferably not using a loop?)

Edit
Report

1 Answer

11

Not using a loop? There is filter builtin:

filter(lambda s: not s.startswith('#'), somestrings)

Note that in Python 3 it returns iterable, not a list, and so you may have to wrap it with list().

answered 2012-08-03T08:01:47.727

Your Answer