I'm looking for a way to loop twice on the same list at the same time as removing some items from this list. I noticed with the code below that looping twice on the same list at the same time as removing elements from this list leads to elements that are not processed.
a=[1,3,1,9]
for i in a:
print(i ,"element from the frist loop for")
for j in a:
if i==j:
p=a.index(i)
del a[p]
print(a ,"list after removing element in the second loop for")
Result:
1 element from the frist loop for
[3, 1, 9] list after removing element in the second loop for
[3, 9] list after removing element in the second loop for
9 element from the frist loop for
[3] list after removing element in the second loop for
The number 3 is not processed because it is not iterated from the first loop
In the first loop we went from 1 to 9 and jumped 3. I want to process also 3 in the first loop.
I understood that the way to loop the list with for loop is frozen by default before running the loop for. In the example the list a must be traversed of the index 0 to 3 since there are 4 numbers in the list so the value 3 has index 1. Knowing that in the first iteration we removed the 1 of the list a, the value 3 no longer has index 1 but 0. But as the index 0 has already been scanned so the value 3 is skipped.
Here true code:
a=[object1,object3,object1,object9]
for i in a:
print(i ,"element from the frist loop for")
for j in a:
if distance(i,j) == 0:
p=a.index(i)
del a[p]
print(a ,"list after removing element in the second loop for")
I try to delete two elements if they are close ( euclidean distance) otherwise I keep them in the list. All these elements are in the same list, hence the double looping on the same list