How to Remove an Element From a List by Index in Python
Created
Modified
Using del Keyword
There is a way to remove an item from a list given its index instead of its value. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
l = [1, 2, 3, 4]
del l[-1]
print(l)
# supports slices:
del l[1:3]
print(l)
[1, 2, 3] [1]
del
can also be used to delete entire variables.
Using pop Method
By default, pop without any arguments removes the last item:
#!/usr/bin/python3
# -*- coding: utf8 -*-
l = [1, 2, 3, 4]
l.pop()
print(l)
[1, 2, 3]
Using slices Operator
This does not do in place removal of item from original list.
For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
l = [1, 2, 3, 4]
# Only positive index
i = 2
l = l[:i]+l[i+1:]
print(l)
[1, 2, 4]
Please note that this method does not modify the list in place like pop and del. It instead makes two copies of lists and one after the index till the last element and creates a new list object by adding both.