April 2, 2025

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 remove 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 for..in loop
We will see that all the numbers appear per 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 eliminate one of the elements of the list that we just created in Python. These will be:

    Remove method
    Pop method
    Judgment of

Remove items 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 (element)

This method will receive as a parameter the element that we want to delete. In such a way that it will remove the first item in the list that matches the item 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 content 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 as follows:
list.pop (position)

In this way, if we want to eliminate the element from 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 be as follows:
1, 4, 3, 4
Remove items from a list with del

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

Thus, if we want to eliminate the element from position 4 we will write the following:
from list [4]

And as it happened in the previous case with the .pop () method
the result list will be as follows.
1, 4, 3, 4, 5

In this way we have already seen the three ways we have to remove elements from a list with Python: the .remove () method
which looks for the first element passed by parameter and the .pop () method
and the sentence of
that eliminate the element attending to the indicated position.

I hope the article is useful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *