The reason you would get [2]
was that you were removing elements from the a
while continuing iterating a
which was very likely to always produce problems.
This is what we expected:
# sudo code
a[0] == b[0] ? if not then continue iterating array b; if yes, a.remove(b[0])
a[0] == b[1] ? if not then continue iterating array b; if yes, a.remove(b[1])
...
Well, but the program would not do as what we expected :(
Presumably, this has something to do with the mechanism of how for
loop worked in python. I did some brief research on this but did not find an exact answer to this. However, according to the result being [2], what was likely to happen underground was the following
(Disclaimer: I didn't look up the source code, and I encourage you to, so the following deduction might be false...)
Since we all know Python is from C, so Python's for
loop is just a shorthand of C's. In C, normally we iterate by index, like for (int index=0; index < size; index++)
. In Python we seemingly have omitted the index and only produced the values, but very likely Python's for
loop was still run under a for
loop with index, which was just we don't see it there. The result of this mechanism was that when you executed a.remove(1)
in the first iteration, you have shortened the length of a
to 2, while the index was incrementing, from 0
to 1
. During the second iteration, the program was looking for a[1]
where 1
was the index incremented from 0
. Since you have removed the first element of a
, the current a[1]
has become the previous a[2]
, which pointed to the value 3
. Then, you compare the 3
in a
with all the values in b
again, then definitely it could find a match and would remove 3 as well. Now it has broken the condition index < size
(in fact, index has been greater than size because the size
has been reduced to 1
after two removes, and the index
would increment from 1
to 2
). So, the iteration was called a stop. Now, when you evaluated a
it would produce [2]
, because the original a[1]
, the 2
, was skipped over the process.
A sample code that could illustrate this is the following, which I have tried:
a = [1, 2, 3]
for n in a:
print(n)
a.remove(n)
You would see only 1
and 3
printed, which proved that 2
was indeed skipped.