. Advertisement .
..3..
. Advertisement .
..4..
Python is an outstanding programming language to use while building machine learning models. It is flexible, powerful, and has the right tools to help you build the most advanced models. This blog post will share the most useful and up-to-date tips on deleting every occurrence of a certain element from a list in Python.
How To Delete Every Occurrence Of An Element From A List In Python?
Option 1: Utilizing remove()
You can delete the item you would like to delete by utilizing remove(). Let’s take a look at an example:
mylist = [8,5,7,8,2,1,7,9,8,6,5,8]
rmv = 8
while rmv in mylist: mylist.remove(rmv)
print(mylist)
Result:
[5, 7, 2, 1, 7, 9, 6, 5]
Option 2: Utilizing for loop
You can delete the item you would like to delete by utilizing the for loop. Let’s take a look at an example:
mylist = [8,5,7,8,2,1,7,9,8,6,5,8]
rmv = 8
for item in mylist:
if(item==rmv):
mylist.remove(rmv)
print(mylist)
Result:
[5, 7, 2, 1, 7, 9, 6, 5]
Option 3: Utilizing _ne_
You can delete the item you would like to delete by utilizing _ne_. Let’s take a look at an example:
mylist = [8,5,7,8,2,1,7,9,8,6,5,8]
rmv = 8
mylist = list(filter((rmv).__ne__, mylist))
print(mylist)
Result:
[5, 7, 2, 1, 7, 9, 6, 5]
Option 4: Utilizing lambda
You can delete the item you want to delete by utilizing lambda. Let’s take a look at an example:
myList = [8,5,7,8,2,1,7,9,8,6,5,8]
rmv = 8
newlist = filter(lambda val: val != rmv, myList)
print(list(newlist))
Result:
[5, 7, 2, 1, 7, 9, 6, 5]
Option 5: Utilizing the filter()
Excepting the solutions mentioned above, utilizing the filter() to delete every occurrence of an element from a List in Python is not a bad way for you.
The filter() method in Python makes it simpler to filter elements. The filter() method accepts two arguments: a function as the first and a set, list, tuple, etc., as the second.
For example:
myList = [2, 1, 3, 5, 1, 1, 1, 0]
myList = list(filter((1).__ne__, myList))
print(myList)
Result:
[2, 3, 5, 0]
In this case, you wish to remove the occurrence of 1 from the list myList. The __ne__ function, which is passed to the filter() function, returns a bool result of True or False depending on whether or not the value 1 is present in the list myList. If the value 1 is already current in the list, it will be discarded. The list() function will then be used to turn whatever the filter() function returns into a list.
Conclusion
We hope you will enjoy our blog post on tips on deleting every occurrence of an element from a List in Python. Please leave a comment if you have any further questions or concerns regarding installing pip on your machine. Thank you for taking the time to read; we are always delighted anytime one of our pieces can give important information on this topic!
Read more
→ Tips On Solving The Error: “Python Pip broken wiith sys.stderr.write(f“ERROR: {exc}”)”
Leave a comment