How To Delete From List In Python?

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



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


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


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



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



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]


del l[:2]

['I', 'python', 'tect']

Leave a Comment