Python list is used to store multiple items in a single variable. The list is very similar to the array type for the C and Java languages. As the list provides dynamic storage items can be added or removed. There are different ways to delete or remove from the list in Python.
Delete with remove()
The list provides the remove()
method in order to remove the specified item from the list. The item value is provided to the remove() item. In the following example we remove the item “tect”.
l = ["I","like","python","tect"]
l.remove("tect")
print(l)
Delete Duplicate Items with remove()
Some times a list may contain duplicate items where same value is used for multiple items. If we try to delete duplicate items with the remove() method only the first occurence of the duplicate item is delete and later occurence of the duplicate item stays.
l = ["python","python","python","python"]
l.remove("python")
print(l)
['python', 'python', 'python']
Deleting Missing Element
In some cases we may try to delete missin element which is not exists. If we try to delete missing element using the remove() method we get the following exception.
l = ["I","like","python","tect"]
l.remove("php")
print(l)
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list
Delete All Items with clear()
The list type provides the clear()
method in order to delete all items in a list. As its name suggests it simply clears the specified list. The clear() method does not require any parameter.
l = ["I","like","python","tect"]
l.clear()
print(l)
Delete Item According to Index with pop()
The pop() method is used to get and delete the first item from the list. We can assign the returned item into a variable or not where it simply delete from the list.
l = ["I","like","python","tect"]
l.pop()
print(l)
Delete Item According to Index with del Keyword
The del
keyword is used to delete specified item or items from a list. The index number or range is provided with the list name to the del keyword.
l = ["I","like","python","tect"]
del l[1]
print(l)
del l[:2]
print(l)
['I', 'python', 'tect'] ['tect']