Skip to content
Advertisement

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

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement