Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first occurrence that matches criteria from a list

Tags:

python

Suppose I have a list of strings:

first item
second item
# first commented item
third item
# second commented item

How do I remove the first item that starts with # from the list?

Expected result:

first item
second item
third item
# second commented item
like image 621
jackson Avatar asked Feb 13 '11 18:02

jackson


2 Answers

>>> items = ["First", "Second", "# First", "Third", "# Second"]
>>> for e in items:
...     if e.startswith('#'):
...             items.remove(e)
...             break
... 
>>> items
['First', 'Second', 'Third', '# Second']
like image 70
user225312 Avatar answered Sep 28 '22 11:09

user225312


items = ["First", "Second", "# First", "Third", "# Second"]
for i in xrange(len(items)):
    if items[i][0] == '#':
        items.pop(i)
        break
print items
like image 45
vz0 Avatar answered Sep 28 '22 10:09

vz0