removing a duplicated item from a python list

43 Views Asked by At

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

There are 2 best solutions below

0
John Gordon On

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)
0
Allan Wind On

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))