List operation: Removing an item
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sun Apr 16 01:11:56 EDT 2006
On Sat, 15 Apr 2006 22:39:37 -0600, Miguel E. wrote:
> I am trying to create a function that removes an item as specified by
> the user. Apparently, the list operation "del list[:]" deletes the
> entire list. Below is the sample function.
If you know the value of the item, and not its position:
somelist.remove("value")
This will raise an exception if "value" is not in somelist.
If you know the item's position:
del somelist[position]
or
somelist[position:position+1] = []
or even:
somelist = somelist[:position] + somelist[position+1:]
(That last example is quite inefficient for lists, but it is a useful
technique to remember for immutable sequences like strings.)
--
Steven.
More information about the Python-list
mailing list