Removing items from a list

Ian Kelly ian.g.kelly at gmail.com
Fri Feb 10 21:22:47 CET 2012


On Fri, Feb 10, 2012 at 1:04 PM, Thomas Philips <tkpmep at gmail.com> wrote:
> In the past, when deleting items from a list, I looped through the
> list in reverse to avoid accidentally deleting items I wanted to keep.
> I tried something different today, and, to my surprise, was able to
> delete items correctly, regardless of the direction in which I looped,
> in both Python 3.2.2. and 2..1 -  does the remove() function somehow
> allow the iteration to continue correctly even when items are removed
> from the midde of the list?

No.  Your test works because you never attempt to remove two adjacent
items, so the skipping of items doesn't end up mattering.  Try the
same thing, but print out the values as you iterate over them:


>>> x = list(range(10))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in x:
...   print(i)
...   if i % 2 == 0:
...     x.remove(i)
...
0
2
4
6
8
>>> x
[1, 3, 5, 7, 9]


Had you attempted to remove any of the odd numbers as well, it would
have failed.

Cheers,
Ian



More information about the Python-list mailing list