Apr-24-2017, 07:50 PM
(Apr-24-2017, 06:41 PM)volcano63 Wrote:For me it looks like appropriate behaviour - from my understanding list iterator (created with for clause) only keeps information about list object and current index. For i-th loop it gives i-th item from the actual list - and if in i-th loop i-th item is different than i-th item before start of loop, well, its not for/iterator problem, but yours. So if you are removing items from the start of the list while looping over it, it looks like it skips every second item, while if you are removing items from the end of the list, it looks like iteration over first half of the list only. Indeed it makes things rather confusing , so its bettter to avoid it...(Apr-24-2017, 03:43 AM)nilamo Wrote: Modifying a list while you're in the middle of iterating over that same list is very dangerous.Usually - from the last time I SNAFUed this way (several years ago ) - iterator skips element on each deletion. It's not dangerous - it's a bug
(Apr-24-2017, 06:47 PM)nilamo Wrote: I think the easy solution is to just iterate over a copy of the list, ie:Such generator expression would not work, it references original list too, changes would "propagate".for x in some_list[:]:
, but then if the list is large (or is a generator and doesn't exist fully yet), that could just eat memory. Maybefor x in (item for item in some_list):
? That way you can modify the original list, without changing how you iterate. Could make for confusing results sometimes, though.