Entry
How do I delete one specific list item?
Apr 5th, 2004 05:25
Michael Chermside, Asher Amoretto,
The answer, of course, depends on how you want to identify the
particular item.
If you know, for instance, that you want to delete the 3rd item in a
list, then you can use the del statement... like this:
>>> x = ['a','b','c', 1, 2, 3]
>>> print x
['a', 'b', 'c', 1, 2, 3]
>>> del x[2]
>>> print x
['a', 'b', 1, 2, 3]
You can also count from the end of the list instead of the beginning:
>>> del x[-2]
>>> print x
['a', 'b', 1, 3]
Or you can delete a whole range of values:
>>> del x[1:3]
>>> print x
['a', 3]
If you want to remove an item from a list and you don't know what
position the item is in, you can use the remove() method:
>>> y = range(10)
>>> y.remove(5)
>>> y
[0, 1, 2, 3, 4, 6, 7, 8, 9]
Finally, if you want to delete LOTS of things at once, the easiest way
is often to use a list comprehension. The following starts with a list
of all numbers 0..19, and then removes all of them EXCEPT multiples of
3 (the 'if' tells what to KEEP, not what to remove):
>>> z = range(20)
>>> z = [x for x in z if x % 3 == 0]
>>> z
[0, 3, 6, 9, 12, 15, 18]