Python List remove() Method
Now, we are going to learn about the remove method. As the name of the method says, this method is used to remove the specified element from the list. This method takes in the element, which we want to remove from the list, as an argument, and removes it from the list. It returns None. Let’s have a look at a simple example, which demonstrates the remove method.
Python List remove() Method
As you can see in the above program, we have a simple list, and then we are trying to remove element 15 from the list. After that, we are simply printing the list. Now, Let’s have a look at the output of the above program.
[23, 12, 45, 29, 31]
As you can see in the output, element 15 is now removed from the list. So, the remove method removes the specified element from the list. The thing is that if we have some element, which occurs repeated times in the list, then only the first occurrence of that element would be removed. Let’s have a look at this example, which demonstrates the same thing.
As you can see in the above program, in our list, there are multiple occurrences of 15, and we are trying to remove the element 15 from the list, so only the first occurrence of the element 15 would be removed from the list, as it can be seen from the output of the above program. Let’s have a look at the output –
[23, 31, 29, 15, 15]
As you can see, the first occurrence of element 15 got removed from the list. So, if we have multiple occurrences of some element in our list, and we try to remove that element from the list, then only the first occurrence of that element would be removed from the list. Now, Let’s say that we need all the occurrences of the element removed from the list, so for that, we need to make use of a loop.
So, what we will simply do is just we will count how many times, the element has occurred in the list, with the help of the count method, and then for that many times, we will run a loop, to execute the remove method, to remove all the occurrences of that element from the list. Let’s have a look at the program –
As you can simply see, in the above program, we are trying to remove all the occurrences of some given element. We are executing the loop for c times, where c is the number of times the element has occurred in the list. Notice the underscore in the loop statement? Well, it is just being used as a variable for the loop. So, the loop executes, and all the occurrences of the element are removed from the list.
The thing is that if we are giving such an element to the remove method, which is not there in the list, then in such a situation, we are going to get into an error. Let’s have a look at that as well.
As you can see in the above program, we are trying to remove an element, which is not there in the list, and in such a situation, we are going to get into an error. You can try executing the program and observing the output of the program yourself.