Jun-21-2018, 06:28 PM
(Jun-21-2018, 06:11 PM)Antigr Wrote: del b[i]If you delete the item at
i
, then everything past that index moves over to the new index. So with the next iteration of the loop, i' refers to the item after what you probably expected it to be.>>> spam = list(range(5)) >>> for ndx in range(len(spam)): ... print(f"{ndx} => {spam[ndx]}") ... del spam[ndx] ... 0 => 0 1 => 2 2 => 4 Traceback (most recent call last): File "<stdin>", line 2, in <module> IndexError: list index out of rangeThat's why you're really not supposed to add/remove items from a list while also iterating over that same list. You could instead build a new list with the things you want to keep, or use a while loop instead of a for loop, for example.
>>> spam = [0 for _ in range(5)] >>> spam.append(1) >>> spam [0, 0, 0, 0, 0, 1] >>> foo = [] >>> for item in spam: ... if item != 0: ... foo.append(item) ... >>> foo [1] >>> # or, if you prefer a comprehension... ... >>> foo = [item for item in spam if item != 0] >>> foo [1] >>> # or, if you prefer functional approaches... ... >>> foo = list(filter(lambda item: item!=0, spam)) >>> foo [1]