Ikram elhail
Ikram elhail

Reputation: 11

how to remove an item from a list in python if that item contains a word

I have a list

a = ['https://example.co/embed/qACAB6TukkU/The.Ha-az.VOST.WEBRip.XviD-ZT.W.avi',
     'https://example.co/embed/l31lsZilT2E/The.Ha-az-ndmaids.FR.HDTV.XviD-ZT.W.avi',
     'https://example.com/embed/soslnnqnmccmplfa/The_Ha-az02_VOST_WEBRip_XviD-ZT_W_avi',
     'https://example.com/embed/pffpmptfpdfqddap/The_Ha-az-_Tale_S2_FRENCH_HDTV_XviD-ZT_W_avi']

I want to remove every item in that list that contain word "VOST" in the link. This what I know and what I have tried:

a.remove('VOST')
print a

Upvotes: 0

Views: 119

Answers (4)

innisfree
innisfree

Reputation: 2495

How about

filter(lambda x: "VOST" not in x, a)

Upvotes: 0

AGN Gazer
AGN Gazer

Reputation: 8378

If you do want to remove items in-place then the following might work for you:

for i in [i for i, v in enumerate(a) if 'VOST' in v][::-1]:
    del a[i]

Alternatively,

for i in reversed([i for i, v in enumerate(a) if 'VOST' in v]):
    del a[i]

or,

for i in reversed(range(len(a))):
    if 'VOST' in a[i]:
        del a[i]

Upvotes: 0

Sheela Singla
Sheela Singla

Reputation: 93

I am a beginner but I don’t think it will work to use a.remove, since removing an item from the list will screw up the indexing for future items. It’s a better solution to create a new list and append items that don’t contain ‘VOST’.

Upvotes: 0

niraj
niraj

Reputation: 18218

You can try iterating through each item and filtering it using list comprehension:

filtered = [i for i in a if 'VOST' not in i]

The above code is similar and better way to following:

filtered = []
for i in a:
    if 'VOST' not in i:
        filtered.append(i)

If you want to use remove, you can iterate through each item and check if word to look for is in item and then remove item. You can try the code below:

Note: This will remove the item from original list, the previous answer creates new list named filtered:

for i in a:
    if 'VOST' in i:
        a.remove(i)

Upvotes: 4

Related Questions