+2 votes
in Programming Languages by (73.8k points)
How can I delete some elements from a list given their index values?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use del statement to to remove an item from a list given its index instead of its value. It can also be used to remove slices from a list or clear the entire list. Check the following examples.

>>> a=[11,12,13,14,15,16,17]
>>> del a[0]
>>> a
[12, 13, 14, 15, 16, 17]

>>> a=[11,12,13,14,15,16,17]
>>> del a[3:5]
>>> a
[11, 12, 13, 16, 17]

>>> a=[11,12,13,14,15,16,17]
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

>>> a=[11,12,13,14,15,16,17]
>>> del a[:]
>>> a
[]


...