Here is a simple question. My task is to loop a list and print each element it has. After each printing, I intend to delete this element from the list as well. My code is:
>> a = [1,2]
>> for x in a:
>> print x
>> a.remove(x)
>> print a
The output is:
>> 1
>> [2]
However, something strange happens here: Only 1 has been printed and it seems after removing 1 from the list, the program jumps out of loop directly. My assumption is after changing the content of the list, the iterator may also be affected, but I'm not very sure. A more safe way is:
>> a = [1,2]
>> b = list(a)
>> for x in b:
>> print x
>> a.remove(x)
>> print a
Could someone please provide me any more advanced explanation?