[Tutor] question about removing items from a list

Lloyd Kvam lkvam@venix.com
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)
> ...
> >>>lista
> ['b', 'd']
> 
> thanks much,
> 
> jck
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582