jackson
jackson

Reputation: 65

Remove first occurrence that matches criteria from a list

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

Upvotes: 6

Views: 9156

Answers (2)

user225312
user225312

Reputation: 131627

>>> items = ["First", "Second", "# First", "Third", "# Second"]
>>> for e in items:
...     if e.startswith('#'):
...             items.remove(e)
...             break
... 
>>> items
['First', 'Second', 'Third', '# Second']

Upvotes: 8

vz0
vz0

Reputation: 32923

items = ["First", "Second", "# First", "Third", "# Second"]
for i in xrange(len(items)):
    if items[i][0] == '#':
        items.pop(i)
        break
print items

Upvotes: 1

Related Questions