I have a python script with removes element from list1 if they are present in list2. Seems preety simple. This is what I did:
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,7,2,1,4,6]
for i in arr1:
print i
if i in arr2:
arr1.remove(i)
print arr1
Expected Output 5
Got this
1
[2, 3, 4, 5, 6, 7]
3
[2, 4, 5, 6, 7]
5
6
[2, 4, 5, 7] # final output
Even after printing i at each iteration I can't figure out why it skips 2 in the first place. But when I repeated the loop 3 times I got expected output.
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,7,2,1,4,6]
for i in arr1:
print i
if i in arr2:
arr1.remove(i)
print arr1
for i in arr1:
print i
if i in arr2:
arr1.remove(i)
print arr1
for i in arr1:
print i
if i in arr2:
arr1.remove(i)
print arr1
Output
1
[2, 3, 4, 5, 6, 7]
3
[2, 4, 5, 6, 7]
5
6
[2, 4, 5, 7]
2
[4, 5, 7]
5
7
[4, 5]
4
[5]
This gives me 5
as output in the final iteration. Can someone tell whats going here. And why it didn't remove all elements at first place and why I need to run them 3 times.
Edit Although list comprehension worked:
arr1[:] = [x for x in arr1 if x not in arr2]
But why isn't my first code working. It is doing the same as what the list comprehension doing it