0

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)
4
  • Why is not working? With your code OUTPUT is [[3, 4], [3, 4, 5, 6]]. What is your expected output? You want delete 3 from first and 6 from second too? Commented Mar 22, 2024 at 10:18
  • This answer will clarify what's happening: stackoverflow.com/a/6260097/7750891 Commented Mar 22, 2024 at 10:21
  • I don't understand how it works and why it deletes first the uneven and then the even numbers? is this how it works? The second thing is when i replace liste[0] with liste.index(a) it does not work anymore. Commented Mar 22, 2024 at 10:27
  • 1
    liste[liste.index(a)] is pointless, just use a. Commented Mar 22, 2024 at 10:29

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much that helped me a lot. I will not edit a list during the iteration.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.