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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With