Removing from a List in Place
sjmachin at lexicon.net
Wed Sep 6 01:29:11 CEST 2006
> > 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?
> >>> alist
> 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 would remove
the third item.
You may have been confused by the OP's obfuscatory example alist = [1,
Consider this equivalent:
| >>> alist = ['foo', 'bar', 'zot']
| >>> for item in alist:
| ... print item
| ... if item == 'bar':
| ... alist.remove(item)
| >>> alist
| ['foo', 'zot']
More information about the Python-list