strange list.remove behaviour in loops
Justin Shaw
wyojustin at hotmail.com
Sun Dec 29 23:08:22 EST 2002
"peter" <peter at nobody.de> wrote in message
news:95gv0vkn4af311fidufibu9dd1q67mn7q8 at 4ax.com...
> hi,
>
> look at the following simple example:
>
> 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.
Here is a workaround, loop on the clone remove from the original:
>>> A = [1, 2, 3, 4, 5]
>>> for a in A[:]:
print a;A.remove(a)
1
2
3
4
5
>>> A
[]
More information about the Python-list
mailing list