+ 1

Delete items from List in python

How to iterate through list and delete the items from it.

11th Apr 2019, 1:36 AM
Prashant Pokhriyal
Prashant Pokhriyal - avatar
3 Answers
+ 3
I wouldn't recommend removing items from a list while iterating through it. I don't know if it's still like this but: Let's say you have list: a = ['a', 'b', 'b', 'c'] When you begin iterating through it, let's say you want to remove some occurrences: for letter in a: if letter == 'b': a.remove('b') print(a) # ['a', 'b', 'c'] You might be wondering: Why is there a 'b' still? Well, that's because when you removed the first b, the index of the second b took it's place, so the next value in the iteration would be 'c'. If you just want to delete all items, list has a function called clear. a.clear() print(a) # [] If you want to remove specific items, use the remove function and pass the item value (not the index). If you want to remove an item in a certain index, use the pop function. (Pop also returns the removed item) I wish you success!
11th Apr 2019, 1:52 AM
Luis Sepúlveda
Luis Sepúlveda - avatar
+ 1
a = ["monkey", "konkey", "donkey", "kingkong"] for i in range(len(a)-1, -1, -1): del a[i]
11th Apr 2019, 8:32 AM
Seb TheS
Seb TheS - avatar
0
def display(a): for i in a: if 'o' in i: a.remove(i) return a L= ['one','book','word','example?','text'] display(L) Expected Result ['example?','text']
11th Apr 2019, 9:08 AM
Prashant Pokhriyal
Prashant Pokhriyal - avatar