[Tutor] question about removing items from a list
Tue, 14 Aug 2001 20:56:52 -0400
You are changing the list while you are stepping through the list in the for statement.
for item in lista returns the 'a' - the first thing in the list.
The processing then removes 'a' from lista. lista is now: 'b','c','d'
for item in lista now returns the SECOND object which is 'c'
It also gets removed, reducing lista to 'b','d'
Now the for item in lista reaches for a THIRD object and hits the end of the list....
The moral is don't delete from a list from within the for statement that is processing that list.
John Kenyon wrote:
> Can anyone explain why the following works the way it does?
> >>>lista = ['a', 'b', 'c', 'd']
> >>>for item in lista:
> ... lista.remove(item)
> ['b', 'd']
> thanks much,
> Tutor maillist - Tutor@python.org
1 Court Street, Suite 378
Lebanon, NH 03766-1358