0
x = len(pdklist)
while x >= 0:
    if pdklist[-1].f in errorlist:
        pdklist.remove(pdklist[-1])
    x -= 1

The while loop does what I want. The for loop only removes every other item in the list. It does print every item.f value though. I originally did it this way and saw it was not right but have not been able to figure out why.

for item in pdklist:
    if item.f in errorlist:
        print(item.f)
        pdklist.remove(item)

Any help appreciated. Probably obvious once someone points it out but I don't see it.

Note: added information that the for loop prints all items but only removes half of them.

ClayD
  • 332
  • 4
  • 14
  • 3
    They do different things. The former is decidedly un-Pythonic whereas the other suffers from a different problem: you can't remove stuff from the list you are iterating over. – tripleee Oct 09 '18 at 04:22
  • 1
    Ahh...did not know that. Yet, it DOES remove every other one. Why would it do that if it is not supposed to remove any? – ClayD Oct 09 '18 at 04:23
  • 1
    It's one of several possible ill-defined outcomes. – tripleee Oct 09 '18 at 04:24
  • 1
    Can you point me to anything that discusses why? My guess from reading other comments is that python keeps an internal pointer to each index number (similar to if I had done ...for i in range(len(pdklist)): and then del or remove by index number. Every time an item gets deleted, the index number changes and things get out of whack. But that is a guess. Is it documented anywhere for me to read about it? Don't go to any trouble looking for it though. Just if you know off hand. – ClayD Oct 09 '18 at 04:43
  • 1
    There's a large number of duplicates for this question; some of them have a more in-depth discussion. But yeah, pretty much like you surmise. – tripleee Oct 09 '18 at 04:46
  • Quick googling brings up https://www.quora.com/In-Python-why-cant-you-remove-elements-from-a-list-with-a-for-loop-but-you-can-with-a-while-loop – tripleee Oct 09 '18 at 04:47

0 Answers0