Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-loop does not go over all objects

Why does this for-loop not go through all items:

 temp = 0

 for br in my_list :
    temp +=1
    #other code here
    #my list is not used at all, only br is used inside here
    my_list.remove(br)

 print temp
 assert len(my_list) == 0 , "list should be empty"

So, assertion fires. Then I added the temp counter and I do see that despite my list having 202 elements, the for loop processes only 101 of them. Why is that?

like image 206
ghostrider Avatar asked Mar 16 '26 03:03

ghostrider


1 Answers

You shouldn't delete from the list you are iterating. Use this if you want to remove stuff

while list:
   item = list.pop()
   #Do stuff

Edit: if you want to know more about pop() look at the python doc

And if order is important, use pop(0). pop() removes the last item by default and if you want to go through your list in order you should use pop(0) that removes the first (index 0) item and returns it.

Edit2: Thanks to user Vincent for the while list suggestion.

like image 61
Atrotors Avatar answered Mar 20 '26 09:03

Atrotors



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!