I have a list of lists containing integers. For example, one line would look like this:
my_list = [11,11,10]
I want to drop the max value, with the purpose of keeping the 2 smallest values.
However, when I run this code it not only drops the max value, but also its duplicate:
>>> [x for x in my_list if x!=max(my_list)]
Output: [10]
Everything works as expected when there are no duplicates in the list:
>>> my_list = [12,11,10]
>>> [x for x in my_list if x!=max(my_list)]
Output: [11, 10]
How can I keep the duplicate value?
CodePudding user response:
You can pass maximum value in the list to list.remove
method; it removes the first occurrence of the value passed.
>>> my_list.remove(max(my_list))
>>> my_list
[11, 10]
PS: It's a mutable operation, so it changes the original list.
Above works only when there's repeated maximum, you can combine it with what you have done:
if my_list.count(max(my_list)) == 1:
my_list = [i for i in my_list if i!=max(my_list)]
else:
my_list.remove(max(my_list))