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

1 Answer

0 votes
by (25.6k points)

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
[]

...