user1756030
user1756030

Reputation: 63

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.

Upvotes: 4

Views: 2121

Answers (5)

Jon Clements
Jon Clements

Reputation: 142106

Something like:

stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]

Modifying an object that you're iterating over should be considered a no-go.

Upvotes: 2

Mark Longair
Mark Longair

Reputation: 467023

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]

Upvotes: 6

AJ.
AJ.

Reputation: 1144

Another but longer way would be to note down the indexes where you encounter pie and delete those elements after the first for loop

Upvotes: 0

Abhijit
Abhijit

Reputation: 63707

Deleting an element during iteration, changes the size, causing IndexError.

You can rewrite your code as (using List Comprehension)

L = [e for e in L if "pie" not in e]

Upvotes: 2

Willy
Willy

Reputation: 635

The reason to why you get a error is because you change the length of the list when you delete something!

Example:

first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).

So rather use something like:

for item in in list:
    if "pie" not in item:
        new list.append(item)

Upvotes: 1

Related Questions