Delete list elements below and above certain value

49 views Asked by At

I have the code below and there are two lists in one list and I want to delete the elements in each list that are higher and lower certain values. The way I tried it does not work because it only deletes some values and I don't understand why.

liste = [[1,2,3,4], [3,4,5,6,7,8,9]]

for a in liste:
    print(a)
    for b in liste[liste.index(a)]:
        print(b)
        if b < 3:
            print(f"{b} < 3")
            liste[liste.index(a)].remove(b)

    for c in liste[liste.index(a)]:
        print(c)
        if c > 6:
            print(f"{c} > 6")
            liste[liste.index(a)].remove(c)

print(liste)
1

There are 1 answers

1
OldBoy On

You should not modifiy a list during an iteration, as it will fail to find all the elements. A better way is to create new lists by using list comprehensions. So in your case above you need to copy only the elements that match the condition thus:

listd = []  # create a new list
listx = [n for n in liste[0] if n > 2] # capture all items greater than 2
listd.append(listx) # add this to listd
listy = [n for n in liste[1] if n < 7] # capture all items less than 7
listd.append(listy) # add this to listd
print(listd) # display the new list