Remove Max and Min values from python list of integers
Asked Answered
T

4

32

I am not completely green to Python, but I am interested in learning/keeping good practices while I develop my skills.

I want to remove the high and low values from a list of numbers, which I know how to do, but am curious if there is a better/preferred way to do this.

mylist = [1, 4, 0, 3, 2]
mylist.sort() #[0, 1, 2, 3, 4]
trimmed = mylist[1:-1] #[1, 2, 3]

I get the desired answer, but did I get the right answer appropriately?

Teamwork answered 13/4, 2011 at 22:56 Comment(0)
S
56

Here's another way to do it if you don't want to change the order of the items:

mylist = [1, 4, 0, 3, 2]
mylist.remove(max(mylist))
mylist.remove(min(mylist))

Assumes that the high/low don't have any duplicates in the list, or if there are, that it's OK to remove only one of them.

This will need to do 2-4 passes through the list: two to find the max and min values, and up to 2 to find the values to remove (if they both happen to be at the end of the list). You could reduce this to one by writing a Python loop to find the max and min in a single pass (and remember the index of each so you can delete the items by index after the loop). However, min() and max() are implemented in C, so replacing them with Python code would probably result in lower performance even if it allowed you to reduce the number of passes.

Subacute answered 13/4, 2011 at 23:0 Comment(2)
Note that doing 4 passes is still probably faster than sorting the list, but if you want mylist to remain and have the trimmed version in trimmed, you should copy it first.Suspension
Yep. trimmed = mylist[:] and then do the manipulations on trimmed.Subacute
D
2

I came up with this because I had duplicates in the list I was trying to modify, so instead of running mylist.remove(min(mylist)) multiple times because it only removes one value at a time I modified it in one line

mylist = [i for i in mylist if i > min(mylist) and i < max(mylist)]
Darton answered 26/3, 2022 at 8:11 Comment(1)
This evaluates min(my_list) and max(myList) once for every item in the list!Subacute
P
0

I had to remove max element and store the list in a variable and same with min element. By using remove function if I stored it in variable it gives none as output. So to store it

arr = [1, 2, 5, 4, 3]
arr.sort()
remmax = arr[0:-1]
remmin = arr[1:]
print(remmax)
print(remmin)
Presentative answered 20/1, 2022 at 15:4 Comment(0)
M
0

You can remove min and max elements in just 2 passes. No sort needed either

mylist = [1, 4, 0, 3, 2]
i, min_elem = min(enumerate(mylist), key=lambda x: x[1])
del mylist[i]
i, max_elem = max(enumerate(mylist), key=lambda x: x[1])
del mylist[i]

[This assumes min and max values have no duplicates in the list]

Maitilde answered 10/5 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.