[Tutor] question about removing items from a list
Wed, 15 Aug 2001 06:28:07 +0200
Allan Crooks wrote:
> On 14 Aug 2001, at 17:42, 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']
> This is happening because of the way the for loop works.
> It keeps on running until it gets to the end of the list. It keeps a
> counter (starting at 0), and increments it until it gets to the end of
> the list (or, more formally, until counter >= length of list).
Well, if you want to be formal about it ;)
It increments the counter, and breaks out of the loop when item =
lista[counter] raises an IndexError. The effect is the same as comparing
with the length of the list though.
"Half of what I say is nonsense. Unfortunately I don't know which half"