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?)
How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.
How do I remove a specific element from a list in Python? The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item.
The pop() method removes the specified index.
[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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With