Removing from a List in Place
John Machin
sjmachin at lexicon.net
Tue Sep 5 19:29:11 EDT 2006
bayerj wrote:
> > I'm going to assume that it's supposed to work like this, but could
> > someone tell me the reasoning behind it? I.E. why is 3 skipped?
>
> Because:
>
> >>> alist[2]
> 3
>
> You are removing the third item, not the second.
This is incorrect.
You may need to remind yourself that the arg of remove is a value to be
searched for and then removed, not an index. del alist[2] would remove
the third item.
You may have been confused by the OP's obfuscatory example alist = [1,
2, 3].
Consider this equivalent:
| >>> alist = ['foo', 'bar', 'zot']
| >>> for item in alist:
| ... print item
| ... if item == 'bar':
| ... alist.remove(item)
| ...
| foo
| bar
| >>> alist
| ['foo', 'zot']
| >>>
HTH,
John
More information about the Python-list
mailing list