strange list.remove behaviour in loops

Erik Max Francis max at alcyone.com
Sun Dec 29 23:36:29 EST 2002


peter wrote:

> Python 2.2.1 (#1, Jul 29 2002, 23:15:49)
> >>> A = [1,2,3,4,5,6,7,8,9]
> >>> for a in A:
> ...     print a
> ...     A.remove(a)
> ...
> 1
> 3
> 5
> 7
> 9
> 
> instead of removing the actual item from the list it removes the next
> one. is this by design? if yes how can i work around it. i don't
> really want to clone the list and remove from the clonelist instead.

This kind of misbehavior is really pretty expected in almost any kind of
language which supports mutable containers.  You really don't want to be
iterating over the container while you're fiddling with it.  If you
really think you know what you're doing and want to fiddle around with
it while inserting and deleting, you should probably be iterating over
the list of _indices_ of the container, not the container itself
(because that won't change as the container does).

The safest way to accomplish what you want is to make a copy of the list
first, iterate over _that_, and then remove the elements from the
original.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ They love too much that die for love.
\__/ (an English proverb)
    The laws list / http://www.alcyone.com/max/physics/laws/
 Laws, rules, principles, effects, paradoxes, etc. in physics.



More information about the Python-list mailing list