0

I'm tring to remove the maximum value from a list that has a repeated maximum value for example: [1,3,6,6,5] the code i use only removes one of the values wihtout removing the other. any ideas why is that happening? the code i use is:

    n = int(input())
    arr = map(int, input().split())
    lst = list (arr)
    for i in lst:
        if i == max(lst):
            del(lst[lst.index(i)])
    print (max(lst))
  • 2
    It's almost always better to make a new list with the ones you WANT to keep. One line: `newlst = [i for i in lst if i != max(lst)]`. – Tim Roberts Apr 17 '23 at 00:50
  • 2
    Changing a list while you iterate through it is problematic. If the input was [3,2,1] would you want to delete all elements? – Allan Wind Apr 17 '23 at 00:51
  • What is the expected behavior if the max value in the list is present more than two times? – Marcelo Paco Apr 17 '23 at 00:57

2 Answers2

1

This code is the problem:

for i in lst:
    if i == max(lst):
        del(lst[lst.index(i)])

As @AllanWind commented, when you call del to remove the item from the list, this changes the size of the list, which causes the outer for i in lst loop to get out of sync with the actual list contents.

Don't add/remove items to a list as you're iterating over it.

For this specific use case, this code would be a lot better:

m = max(lst)
while m in lst:
    lst.remove(m)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

You could use a filter (and if you wish assign the result to the same lst):

lst = [1, 3, 6, 6, 5]
lst2 = list(filter(lambda f: f != max(lst), lst))
Allan Wind
  • 23,068
  • 5
  • 28
  • 38