4 Ways to Delete From a List in Python

4 Ways to Delete From a List in Python

How to remove from a list with clear, pop, remove, and del

Image for postPhoto by Gary Chan on Unsplash

There are several ways to remove an element from a list in Python.

Let?s look at the four main ones: the clear, pop, andremove methods, and the del operator.

In the following examples, I?ll use a common list to demonstrate each method. For simplicity, let?s assume that the list used is l = [2, 3, 4, 5].

Clear

The clear method removes all elements from the list. This is useful when you no longer need any of the list?s elements and just want to re-use the same list object for new data.

Example

After we call clear , the list is empty ? nothing is returned:

l# l = [2, 3, 4, 5]l.clear()# l =

Pop

The pop method removes the list element at a certain index and returns the value of the element once it?s removed. This is useful if you want to remove an element from a list, but still want to use that element?s value for other purposes.

Example

When we call .pop(0), the element at index 0 is removed from the list and returned:

l# l = [2, 3, 4, 5]res = l.pop(0)# l = [3, 4, 5]# res = 2

Remove

The remove method removes a list element by value instead of by index. In cases where multiple elements match the provided value, the first matching element (the one with the lowest index) is removed. This is useful when you know in advance which element needs to be removed and don?t want to waste resources finding its index before removing it.

Example

When we call .remove(3), the second element in the list is removed (3), and nothing is returned:

l# l = [2, 3, 4, 5]l.remove(3)# l = [2, 4, 5]

Del

Finally, we have the del operator. This is a Python built-in keyword, instead of a list method. The del operator allows you to remove elements from a list by indice(s). This approach is useful because it can remove both single elements, by providing a single index, as well as multiple elements, by providing a range of indices.

Examples

First, we will remove one element from the list. When we del l[0] , we?re removing the element at index 0 from the list.

l# l = [2, 3, 4, 5]del l[0]# l = [3, 4, 5]

Now, to remove multiple elements, we can use a slice of the list. When we del l[0:2] , we are removing the elements at indices 0 and 1, since we specified the range of indices ? 0, 2 (the lower bound is inclusive and the upper bound is exclusive):

l# l = [2, 3, 4, 5]del l[0:2]# l = [4, 5]

16