Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the lowest numbers from a list

I'm trying to write a function that removes the lowest numbers then averages the remaining numbers in the list. Is there a way to remove the lowest two or more numbers from a list without using sorted() or sort()? Like using min() combined with range().

What I have so far:

lst = [90, 100, 95, 95]
lst.remove(min(lst))
print(sum(lst) / len(lst))
like image 938
DA_F Avatar asked Jan 21 '26 06:01

DA_F


1 Answers

list.remove deletes the first matched value in the list. In order to remove all occurrences of the current lowest number, you'll have to call it list.count(min(list)) times.

Here's the function that removes n smallest numbers from lst and that doesn't involve list.remove:

def remove_n_smallest(lst, n):
    for _ in range(n):
        m = min(lst)
        lst[:] = (x for x in lst if x != m)

And here's the example for lst from your question:

>>> remove_n_smallest(lst, 2)
>>> lst
[100]
>>> sum(lst) / len(lst)
100.0
like image 193
vaultah Avatar answered Jan 23 '26 18:01

vaultah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!