In this tutorial, we will learn how to remove an item from a list in python. We can divide this problem into three categories: removing an element_ using its value, _using an index and remove all elements.
This tutorial will show you how to remove an element using its value, how to remove using an index and how to remove all elements from a list in python.
Actually, we already have inbuilt methods for all of these operations. Different methods are available for removing list items.
This method is used for removing an item from a list using its value._ remove() _method is defined as below :
As you can see that we don’t need to import any other module to use this method. This is an inbuilt method of a list in python. It takes one value as the parameter, i.e. the value you want to remove. In the above picture, it will remove ‘c’ from the list. If the value is not found, it will raise ValueError.
Another method of removing an element from a list is pop. This method takes the index of the element to remove as the parameter. It returns that indexed element from the list. This value is optional. If we don’t pass it, it will return the last element of the list.
This method is useful if we want to use the removed value later. You can call this method and store the returned value in a separate variable to print it out to the user or to use it in future.
So, both remove and pop methods are used to remove a single element from a list. The following are the two main differences between these two methods :
- remove takes the element to remove as its argument and pop take the index of the element as an argument.
- remove will simply remove the item. It doesn’t return any value. But pop removes the element and returns it.
For removing all elements from a list in python, we can iterate the list and remove each item one by one using the remove or pop method. But Python provides us with one simple method to remove all elements of a list, clear().
del is a powerful statement for removing list values in python. Using it, we can remove an element using a specific index. pop method also takes one index and remove the element at this index. The only difference is that pop returns a value and del doesn’t return a value.
Using del, we can either remove one specific value, remove slice from a list or clear the entire list.
remove, del, clear and pop are useful methods for removing single or multiple items from a python list. Try to run the above examples and drop one comment below if you have any queries.
- Python program to convert a list to string
- Python add and remove elements from a list
- Four different methods to check if all items are similar in python list
- Python program to find the middle element of a random number list
- Python program to find out numbers in a list divisible by two numbers
- Python program to iterate over the list in reverse order