Remove elements from a list with Python

In a previous article we saw how we could add elements to a list in Python, now we are going to see the complementary and we will learn how to eliminate elements from a list with Python. To do this, the first thing we will do is create a list of elements, in this case a simple list with numbers.

list = [1,4,3,4,5]

If we go through the list using a simple loop for..in we will see that all the numbers appear in the console.

for element in list:
    print (element)

By console we will have all the numbers:

1, 4, 3, 4, 5

Now we are going to see three mechanisms to be able to delete one of the elements from the list that we just created in Python. These will be:

  • remove method
  • Pop method
  • Judgment of

Remove elements from a list with remove

In this first case we are going to use the .remove() method. This method can be executed directly on the list, so its syntax is:

list.remove(item)

This method will receive as a parameter the element we want to delete. In such a way that it will remove the first element from the list that matches the element passed as a parameter. That is why if we want to eliminate the first element that matches the number 4 we will write the following:

list.remove(4)

By dumping the contents of the list we obtain the following:

1, 3, 4, 5

Remove items from a list with pop

Another alternative is to use the .pop() method. This method is also invoked on the list and allows us to eliminate the element that is in the position passed as a parameter. The syntax will be the following:

list.pop(position)

In this way, if we want to eliminate the element in position 4 we will write the following:

list.pop(4)

In this case we have eliminated element 5 that is in position 4 and the list will look like this:

1, 4, 3, 4

Delete elements from a list with del

The third way to delete a list with Python is the del statement. This statement allows you to eliminate any element, including the element from a position in the list. Its syntax will be the following:

del list[position]

Thus, if we want to eliminate the element in position 4 we will write the following:

del list[4]

And just as happened in the previous case with the .pop() method, the result list will be the following.

1, 4, 3, 4, 5

In this way we have already seen the three ways we have to eliminate elements from a list with Python: the .remove() method that finds the first element passed by parameter and the .pop() method and the del that eliminate the element based on the indicated position.

I hope the article is useful to you.

Leave a Comment