Home > OS >  Python - bug - deleting elements from a list
Python - bug - deleting elements from a list

Time:11-02

In an exercise I'm supposed to have a program that asks for multiple inputs and the program should delete the largest and smallest n numbers.

My attempt:


def outliers(lst, n):

    new = sorted(lst)

    for i in range(0, n):
        del new[i]
        del new[len(new) - i - 1]

    return new

def main():
    lst = []
    n = int(input("Enter a non-zero number: "))
    while n != 0:
        lst.append(n)
        n = int(input("Enter a non-zero number: "))

    print(f"the list without the 2 outliers are: {outliers(lst, 2)}")

main()

Bug:

Enter a non-zero number: 1
Enter a non-zero number: 2
Enter a non-zero number: 5
Enter a non-zero number: 8
Enter a non-zero number: 9
Enter a non-zero number: 0
the list without the 2 outliers are: [8]

Process finished with exit code 0

The program should return a list [5]. I tried to run parts of the program, i know the error must be that for loop that I'm using. But it seems correct to me. Can someone tell me why it's not working the way it should?

CodePudding user response:

As you delete element at the beginning, the other elements move forward, just use the slice notation

def outliers(lst, n):
    return sorted(lst)[n:-n]


print(outliers([1, 2, 5, 8, 9], 2))  # [5]
print(outliers([1, 2, 5, 8, 9], 1))  # [2, 5, 8]

CodePudding user response:

try this:

def outliers(lst, n):

    new = sorted(lst)

    for i in range(0, n):
        del new[0]
        del new[len(new) - 1]

    return new

we should always delete new[0], because original first elem had gone

  • Related