strange list.remove behaviour in loops

Mel Wilson mwilson at the-wire.com
Mon Dec 30 08:57:55 EST 2002


In article <mcloua.go3.ln at beastie.ix.netcom.com>,
Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
>peter fed this fish to the penguins on Sunday 29 December 2002 07:45 pm:
>> 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.
>>
>        I suspect it /is/ removing the actual item. What may be happening,
>however, is that the next pass is seeing the /position/ that is next in
>line, but your remove has shifted everything left one place. [ ... ]

This is true.  You can see it in

Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> A = [1,2,3,4,5,6,7,8,9]
>>> for a in A:
...   print a, A
...   A.remove(a)
...
1 [1, 2, 3, 4, 5, 6, 7, 8, 9]
3 [2, 3, 4, 5, 6, 7, 8, 9]
5 [2, 4, 5, 6, 7, 8, 9]
7 [2, 4, 6, 7, 8, 9]
9 [2, 4, 6, 8, 9]
>>>


        Regards.        Mel.



More information about the Python-list mailing list