I am iterating through a list an sometimes I remove an element from another list. Instead of removing the element from the other list the for loop skips the entire actual iteration. I found a solution to that, but I don't understand it quite well.
Here is a code example. It's two times the same except that I commented out the line final_dt_list.remove(dt)
:
dt_list = [3600, 2700, 1800, 900]
final_dt_list = dt_list
for dt in dt_list:
print(dt)
if not((3600/dt).is_integer()):
print('skipped '+str(dt))
final_dt_list.remove(dt)
continue
print('ok')
print('\n \n')
dt_list = [3600, 2700, 1800, 900]
final_dt_list = dt_list
for dt in dt_list:
print(dt)
if not((3600/dt).is_integer()):
print('skipped '+str(dt))
#final_dt_list.remove(dt)
continue
print('ok')
The result that I get is:
3600
ok
2700
skipped 2700
900
ok
3600
ok
2700
skipped 2700
1800
ok
900
ok
As you can see in the result of the first loop, 1800 is not printed, just nothing happens.
What worked for me finally was creating a list of items I want to remove. And than create a new loop that iterates through the items I want to remove. This new loop will then remove each element from final_dt_list.
See solution code here:
for r in removed:
final_dt_list.remove(r)
Why does that work now and not the example above? I'm confused.
Thanks in advance!