list remove

Paul Sidorsky paulsid at home.com
Tue Oct 2 13:41:30 EDT 2001


steven.smith at LEVEL3.com wrote:

> >>>foo = [1, 2, 3, 4, 5]
> >>>for bar in foo:
> ...     foo.remove(bar)
> 
> >>>foo
> [2, 4]

> Is this an error on my part, pythons list type or am I misinterpretting what
> remove does?  I have tried this on both 2.1 and 1.5.2.

Each time an item is removed, the others get shifted up one.  So what is
essentially happening is this:

>>> foo = [1, 2, 3, 4, 5]
>>> i = 0
>>> foo
[1, 2, 3, 4, 5]
>>> foo[i]
1
>>> foo.remove(foo[i])
>>> i += 1
>>> foo
[2, 3, 4, 5]
>>> foo[i]
3
>>> foo.remove(foo[i])
>>> i += 1
>>> foo
[2, 4, 5]
>>> foo[i]
5
>>> foo.remove(foo[i])
>>> i += 1
>>> foo
[2, 4]

Possible solutions are to either remove going from back-to-front (using ranges)
or to use a while loop and maintain your own index counter, incrementing it
only each time you find something you don't want to delete.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid at home.com                      http://members.home.net/paulsid/




More information about the Python-list mailing list