Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?)

like image 558
theRealWorld Avatar asked Aug 03 '12 07:08

theRealWorld


People also ask

How do you exclude items from a list in Python?

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 character from a list in Python?

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.

Which method removes the specified index?

The pop() method removes the specified index.


2 Answers

[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.

like image 102
jamylak Avatar answered Oct 17 '22 06:10

jamylak


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().

like image 36
hamstergene Avatar answered Oct 17 '22 07:10

hamstergene