简体   繁体   中英

while loop with iterator in python which keeps on changing

I have a snippet where I need to iterate over a list of items and remove the item whose job is done and continue looping on the remaining items.

as per python I can pass l to check condition for while loop as below :-

l = [node1, node2, node3]
while l:
    #do something
    for t in l:
        if t[wt] > 10:
            l.remove(t)

but as per this guide , it is not a good practice to modify a list while iterating over it.

So I changed my code to :-

l = [node1, node2, node3]
while len(l)>0:
    #do something
    for t in l:
        if t[wt] > 10:
            l.remove(t)

But then I see below pylint warning :-

[pylint] C1801:Do not use len(SEQUENCE) as condition value :- reference

Now what should be the approach here to handle this while loop with list which would not violate any of the above practices ?

By using len(l) in your condition, you didn't improve your code, it remains with the same error (removing items while iterating in the inner for loop), you just degraded the code, adding an irrelevant warning.

You are still removing elements while iterating in the inner loop.

for t in l:
    if t[wt] > 10:
        l.remove(t)

This could induce a subtle bug: if 2 consecutive elements need to be removed, the second one is skipped, and your code executes twice the processing you've eluded before the loop.

Instead, you should recompute l in the end using a list comprehension

l = [node1, node2, node3]
while l:
   # do something then rebuild `l` 
   l = [t for t in l if t[wt] <= 10]

more about this: How to remove items from a list while iterating?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM