[Tutor] removing items from a list
alan.gauld@bt.com
alan.gauld@bt.com
Mon, 14 Oct 2002 12:15:17 +0100
> This doesn't work, I'm not sure why. Mabye item isn't a
> refence to the list item, but just has the same value.
>
> for item in list:
> if item == data: del item
This deletes item but the list still has a reference to it.
ie item no longer points at the object but the list does!
> This works, its ok, but still seems like there should be something
> cleaner if not faster.
Actually it doesn't quite work!
> i=0
> for item in list:
> if item == data:
> del list[i]
> i=i+1
Two adjacent items that equal data will only result in
one being deleted:
a
b <---- item
b
c
becomes
a
b
c <----- item after an iteration of the loop with item = b.
You really need to use a while loop to do this manually:
i = 0
while i < len(list):
if list[i] == data: del list[i]
else: i += 1
A better solution is to use the filter() function or a list
comprehension
list = filter(lambda x: x != data, list)
list = [item for item in list if item != data]
filter is designed to filter out items that match the test
function. comprehensions are designed to look a little
like set notation in math....
Be aware that the performance may not be much better than
the loops, but they look nicer...
HTH,
Alan G.