Python list.remove() skips next element in list

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

Leave a Comment