Want to remove an element at a given position i
in a list a
?
Simply use the del a[i]
operation to remove the element at index position i
.
Here’s the Python code example:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] del a[2] print(a) # [0, 1, 3, 4, 5, 6, 7, 8, 9] del a[0] print(a) # [1, 3, 4, 5, 6, 7, 8, 9] del a[-1] print(a) # [1, 3, 4, 5, 6, 7, 8] del a[2:4] print(a) # [1, 3, 6, 7, 8] del a[::-1] print(a) # []
This is the easiest way of removing a list element at a certain position. You can even use slicing to remove a whole subsequence of the list. For example, the slice operation del a[2:4]
removes the elements with indices 2 and 3 from the list a
.
If you lack slicing skills, check out my “Coffee Break Python” book package (with free bonus Python slicing book).