.remove() and .copy()
I get that you can't properly use .remove() in a for loop, but why? What's the logic that makes the result in the example leave index 1 & 3 (IIRC)? Also, if .copy() doesn't actually save a new instance of the variable and you're still editing the original variable.... How does that function? How does .copy() make it possible to use .remove() in a for loop? I get that it does, but why and how?
I get that you can't properly use .remove() in a for loop, but why?
Let's say you had code like this:
numbers = [0, 1, 2, 3, 4, 5] for number in numbers: numbers.remove(number)
for loop starts Python pulls out the first item of the
numbers collection and assigns it to
number as I'm sure you already understand, but how does Python do that? It simply uses the index the same way as you would if you were to do so manually. So behind the scenes the first iteration of the loop essentially looks like this:
numbers = [0, 1, 2, 3, 4, 5] number = numbers # Index 0 contains 0 numbers.remove(number) # Remove 0 from list
Well what happens the next iteration? Python pulls out the second item by simply increasing the index it used in the previous iteration. So after two iterations the loop would essentially have executed code similar to this:
numbers = [0, 1, 2, 3, 4, 5] number = numbers # Index 0 contains 0 numbers.remove(number) # Remove 0 from list number = numbers # Index 1 contains 2 numbers.remove(number) # Remove 2 from list
Now looking at the comments you will notice that we have suddenly skipped past the number 1, why? Well because when 0 was removed the indexes all shift back by one. The first item is now 1, the second 2, the third 3 and so on, since 0 is no longer an item in the list.
for loop has not taken this change into account, it assumes that the indexes are unchanged which is why it ends up skipping the number 1. And that behavior continues in the subsequent iterations and results in the loop essentially skipping every other item in the list.
Also, if .copy() doesn't actually save a new instance of the variable and you're still editing the original variable.... How does that function?
I think you must have misunderstood something about how
copy works. The method does exactly what the name implies, it creates a copy of the variable, and this copy is entirely independent of the original. Modifying the copy will not affect the original in any way.
fady, not quite. It makes a copy of the list at the moment of creating the loop, then references that copy as it removes items from the original. The copy isn't altered during the loop at all and then... I believe it is discarded afterwards as it isn't assigned a variable. That's my understanding, at least.