Search code examples
pythonlistmedian

list.remove(x): x not in list, when trying to find median


Could anyone tell me why this isn't working? I got error saying:
ValueError: list.remove(x): x not in list.

But if I try print max; it prints 9, and also if I print min; it prints 1.

list = [3,1,4,9,5,7]
max = list[0]
min = list[0]

list = list[:]
while len(list)> 2:
        for i in list:
                if(i > max):
                        max = i
                elif(i < min):
                        min = i
        list.remove(min)
        list.remove(max)

print list  

I need to remove max and min element from list, until there are only 2 elements in order to get the median of the list.


Solution

  • Your problem is that you only initialize the min and max variables once, outside the while loop.

    Your code will work if you initialize inside the loop.

    This code works. Note that I changed the variable names to not be Python built-ins. You shouldn't use names that "shadow" built-ins; for example, list is a built-in type, so you shouldn't use list as a variable name.

    lst = [3,1,4,9,5,7]
    
    lst = lst[:]
    while len(lst)> 2:
            max_val = lst[0]
            min_val = lst[0]
            for i in lst:
                    if(i > max_val):
                            max_val = i
                    elif(i < min_val):
                            min_val = i
            lst.remove(min_val)
            lst.remove(max_val)
            print lst
    

    Note that your code is tremendously inefficient and slow. You could speed it up a bit by using the built-in functions max() and min() but the algorithm is still inefficient.

    The best thing is to just sort the list, and then pick the single value from the middle of the list (for an odd-length list) or average the middle two values (for an even-length list). Or simply use one of the built-in functions that Python provides.

    How to find Median