Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove mode entirely

I am trying to write a method that removes the mode entirely from a list. I’ve looked up other articles to use a for loop but it doesn’t entirely get rid of the mode from the list like it needs to.

this is what my list would look like before I get rid of the mode entirely from a list.
list = 1,3,4,6,3,1,3,
I have already tried the .remove function but it only removes 1 of the numbers
my expected outcome
list = 1,4,6,1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

mylist.remove(x) removes only the first occurrence of x from the list.

If you think there may be more than one, use a while loop:

while 3 in mylist:
    mylist.remove(3)

If the list is long and/or there might be several 3s in the list, this approach would be more efficient, as it only iterates over the list once:

mylist = [item for item in mylist if item != 3]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading