Python list.remove() skips next element in list

前端 未结 6 1746
夕颜
夕颜 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:45

    Others have explained that you should not remove elements from an array you are iterating over; however, if you traverse the array backwards, there is no problem.

    The most compact way to solve this problem (assuming you don't need a copy of the original array after you are done) is to use the reversed() function, as in

    for square in reversed(squares)

    This will start iterating from the end of the array, and work backwards. Taking out elements in this way will not affect the rest of the code, since you are not changing the order of elements you have not yet visited. I think this is the most elegant way to solve this. I learnt this trick here

提交回复
热议问题