How to remove an item from a python list :
In this tutorial, we will learn how to remove an item from a list in python. We will learn how to remove an element using its value from a list and how to remove using an index. Also, we will learn how to remove all elements from a list.
Python provides different methods for list deleting operation. Let’s take a look at them one by one :
Removing item using list.remove(x) :
remove() method is defined as :
It will remove the ‘c’ from the list. If the value is not found, it will raise ValueError.
Removing item using list.pop(i) :
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.
The first print will print out c and the second one will print out f as the output.
Removing all elements from a list :
To remove all elements of a list, we can use clear() method. For example :
It will print one empty list  as the output.
Removing elements using del :
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.
You might also like :
- 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