Python list del: How to remove or delete an element from a list

Python built-in function del deletes the element of a list.

a = ['Book', 'Note', 'Pen']

del a[1]

print(a)  # ['Book', 'Pen']

The element of a, whose index is 1, is removed. This function can remove items in a row.

a = ['Book', 'Note', 'Pen']

del a[0], a[1]

print(a)  # ['Note']

['Book', 'Note', 'Pen']
-> [Note', 'Pen']
-> [Note']

del raises the exception if the index is out of range.

a = ['Book', 'Note', 'Pen']

del a[4]

# IndexError: list assignment index out of range


Powered by Markdown