Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for substring in element in a list an deleting the element

I have a list and I am trying to delete the elements that have 'pie' in them. This is what I've done:

['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
    if "pie" in list[i]:
         del list[i]

I keep getting list index out of range, but when I change the del to a print statement it prints out the elements fine.

like image 451
user1756030 Avatar asked Dec 21 '22 14:12

user1756030


1 Answers

Instead of removing an item from the list you're iterating over, try creating a new list with Python's nice list comprehension syntax:

foods = ['applepie','orangepie', 'turkeycake']
pieless_foods =  [f for f in foods if 'pie' not in f]
like image 50
Mark Longair Avatar answered May 06 '23 11:05

Mark Longair