Python list.remove() skips next element in list

前端 未结 6 1710
夕颜
夕颜 2020-12-16 01:27

Python, but not programming, newbie here. I\'m programming with lists and have run into an interesting problem.

width = 2
height = 2

# Traverse the board
de         


        
6条回答
  •  时光说笑
    2020-12-16 01:50

    When you are accessing a list in Python and remove an element, the list becomes shorter. Simple example: take the list 1,2,3,4,5, and remove the prime numbers > 1.
    If you look at the second element (2) and decide to remove it, you end up with a list that goes 1,3,4,5 Now you look at the third element (you have already looked at the second one), and you find it's 4. That's not prime, so you go to the fifth element - 5. Remove it.
    Result: you have 1,3,4,5. If you had started from the other end of the array, things would work just fine. Make sense?

    EDIT: I have created another answer below - other posters gave a better explanation of the problem than I gave here, but I think I have a more elegant solution.

提交回复
热议问题