list remove
James_Althoff at i2.com
James_Althoff at i2.com
Tue Oct 2 12:57:38 EDT 2001
The python tutorial at
http://www.python.org/doc/current/tut/node7.html#SECTION00710000000000000000
0 has the section more on lists where it gives the function remove(x). I
am
trying to use this function to delete elements out of my list, but it only
deletes every other list.
>>>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.
Thanks.
Steve
================
It's not a good practice to delete items from a list when iterating over
that same list. Iterate over a copy of the list instead.
Just change
for bar in foo:
to
for bar in foo[:]: # now you are iterating over a copy of foo
Jim
More information about the Python-list
mailing list