Python: Remove items from a list while iterating in Python

Posted by xApple on Stack Overflow See other posts from Stack Overflow or by xApple
Published on 2010-04-13T11:44:12Z Indexed on 2010/04/13 11:52 UTC
Read the original article Hit count: 292

Filed under:
|
|
|

My problem is simple: I have a long list of elements that I want to iterate through and check every element against a condition. Depending on the outcome of the condition I would like to delete the current element of the list, and continue iterating over it as usual.

I have read a few other threads on this matter. Two solutions seam to be proposed. Either make a dictionary out of the list (which implies making a copy of all the data that is already filling all the RAM in my case). Either walk the list in reverse (which breaks the concept of the alogrithm I want to implement).

Is there any better or more elegant way than this to do it ?

def walk_list(list_of_g):
    g_index = 0
    while g_index < len(list_of_g):
        g_current = list_of_g[g_index]
        if subtle_condition(g_current):
            list_of_g.pop(g_index)
        else:
            g_index = g_index + 1

© Stack Overflow or respective owner

Related posts about python

Related posts about list