0

For every element in a for loop, I want to check if the element satisfies some condition. If yes, I want to do something to it; if no, I want to add it to the end of the list and do it later.

I'm aware that modifying loops while looping is bad, but I want to do it anyway, and want to know how to do it correctly.

for i in list:
    if something(i):
        do(i)
    else:
        #append to end of list, do later
        list.remove(i)
        list.append(i)

This piece of code mostly works, but causes me to skip the element after the removed i while iterating. How do I work around that?

2 Answers2

0

Realized just after asking that I don't even need to remove if I'm only ever going to iterate through the list once - if I just append, I'll be able to operate on the element once everything else is finished.

In other words, this works:

for i in list:
    if something(i):
        do(i)
    else:
        #append to end of list, do later
        list.append(i)
0

I'm pretty sure there is no correct way to modify a list while looping over a list. In particular, removing objects from a list will cause issues (see strange result when removing item from a list).

I would consider making additional lists, one for your results, one temp list for the elements you have left to process. Note that in my example, tmp1 is your input list.

tmp1 = [values to process]
tmp2 = []
results = []
while(tmp1)
    for i in tmp1:
        if something(i):
            results.append(i)
            do(i)
        else:
            tmp2.append(i)
    tmp1 = tmp2
    tmp2 = []
ividito
  • 321
  • 3
  • 14