Python program to remove all occurrence of a value from a list
Python: remove all occurrence of a value from a list :
In this tutorial, we will learn how to remove all occurrence of a value from a list in python. For example, if the list is [1,1,2] and if we will remove all occurrence of 1, it will become . I will show you two different ways to solve this problem. Let’s take a look :
Below examples are available here on Github.
Method 1: Using a while loop :
Using one while loop, this program can be solved easily. The main idea is to run a while loop continuously, check for any assistance and remove that value on each iteration. Means, for the example above, we will check if the value 1 exists or not in the list on each iteration of the while loop. If it exists, we will remove it, and if not, we will exit the program. The program will look like as below :
The commented numbers in the above program denote the step number below :
- Ask the user to enter the size of the list. Read it and store it in the list_size variable.
- Create one empty list user_list to store all user input numbers.
- Run one for loop. Ask the user to enter values for the list. Read it and append to the list.
- Print the user input list to the user.
- Ask the user to enter the number to remove from the list. Store it in the flag variable.
- Run a while loop and check continuously if the flag exists in the user_list or not. If yes, remove it from the list. The remove() method removes the first occurrence of a value from a list. So, we need to call it multiple times if that number has multiple occurrences in that list.
- Print out the final list to the user.
Sample Output :
The main problem with this approach is that we are checking for the existence of a value multiple times in the list. So, we are scanning the list multiple times. We can also optimize it to scan only one-time using list comprehension like below.
Method 2: Using list comprehension :
We can scan the whole list only one time to remove all occurrence of a specific value.
The main benefit of this method than the previous one is that we need to scan the list only for one time. If you have a list of very large size, you should use this method to optimize your runtime. The only problem is it will create one different list unlike the previous one.
As you can see the output is the same as the previous one.
We have seen two different ways to remove all occurrence of a value in a list in python. It totally depends on you which one you want to use. The second method is more preferred to use if you are dealing with a large size of the list and the first one is for changing the original list itself. Go through the programs we have explained above and drop a comment below if you have any queries.