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
Don't modify lists that you are iterating over!
Instead, do something like:
for square in squares[:]:
so that you're iterating over a copy of the list while still changing the original.
The statement for square in squares
just visits each item in the list in order: squares[0]
, then squares[1]
, then squares[2]
, and so on until it runs out of squares.
Removing squares[0]
shifts all the other items in the list to the left one slot; the original squares[1]
is now squares[0]
, so the for loop will skip over it.
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
Removing array elements inside for loop is not advisable because for loop checks indexes in a order and removing an element inside loop shifts proceeding elements left one index, if you want to do it then use reversed()
arr = [1,2,3,4,5]
for ele in reversed(arr): condition: arr.remove(ele)
You are removing from a list while iterating over it. This is not a good idea.
There are other ways to do what you are trying, one of which is to track the list indices of all items that you want to remove from the list and then remove them outside your for-loop
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.