Finding a substring in an element in a list deletes an element (Python)

I have a list, and I'm trying to remove items that have "pie" in it. This is what I did.

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

I keep indexing the list index out of range, but when I change the del to the print statement, it renders the elements perfectly.

+4
source share
5 answers

Instead of removing the item from the list that you are repeating, try creating a new list using Python nice syntax:

 foods = ['applepie','orangepie', 'turkeycake'] pieless_foods = [f for f in foods if 'pie' not in f] 
+6
source

Removing an item during iteration resizes by raising an IndexError.

You can rewrite your code as (using List Consrehension)

 L = [e for e in L if "pie" not in e] 
+2
source

Sort of:

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

Changing the object you are repeating should be considered as "no-go."

+2
source

The reason you get the error message 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!). 

Rather use something like:

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

Another, but longer way would be to mark the indices where you encountered the pie and remove these elements after the first cycle of the cycle

0
source

Source: https://habr.com/ru/post/1440514/


All Articles