0

How to iterate through a list and remove certain elements from it using pop().

Here I am trying to iterate through a list called "lst" and I want to remove all the zeros from it. So I used a for loop and the built in enumerate() function. I used the enumerate function bcz I want to get the index of the items in the list and then remove them using the pop() function. I don't wanna use remove() bcz I want to get the values of the removed elements. Inside the if block, I checked to see if an element is equal to 0, and also it shouldn't be a "False" bcz False is considered as 0. >>>False == 0 >>>True So, if the element is == 0 and if the element is not the boolean "False", then I want to remove that element using its index. Here is the code that I've written: lst = [False,1, 0, 2, 0, 0] for index, element in enumerate(lst): if element == 0 and element is not False: lst.pop(index) print(lst) when I run this code, the print() function returns: [False, 1, 2, 0] As u can see, there is still one 0 that isn't removed. I don't understand why. please help me, this seems like an easy problem but I still can't figure it out.

1st Nov 2020, 9:22 AM
Hosea
1 Respuesta
+ 6
It is because you are alterning the list while traversing it. This will mess up whenever there would be repetitions in the list. For example :- [2,0,0] when you will pop first zero then the list will shrink to [2,0] but according to the loop statment, now loop counter have to incremented by one, which means it will try to access 3rd member of the list which doesn't exist in this case and loop will break. A simple fix it to travers on a copy of the list instead of the real one
1st Nov 2020, 9:46 AM
Arsenic
Arsenic - avatar