Reputation: 1208
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?)
Upvotes: 9
Views: 34183
Reputation: 133634
[x for x in my_list if not x.startswith('#')]
That's the most pythonic way of doing it. Any way of doing this will end up using a loop in either Python or C.
Upvotes: 27
Reputation: 24439
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()
.
Upvotes: 11