Pages

Saturday, August 22, 2009

Python remove list elements in-place

   In Python, If you want to remove elements from a list based on a condition, a normal iteration will not work correctly:

for elem in list:  
    if cond(el):
        list.remove(elem)

In this case, for example if the list contains 10 elements, all invalid, only 5 of them will be removed, because of the internal counter on the list, that is used by the iteration. Python offers 2 simple approaches(Method 2 and 3 below). These 2 methods create a new list. Another solution will be to remove elements in-place, without using additional memory(Method 1). The code for this is self-explaining. The index keeps track of where we are in the list and need to put valid elements. After that, the other elements can be deleted.

# In-place filter of a list
# Keeps elements matchign condition
def filter_list(list, cond):
    to_idx = 0
    for el_current in list:
        if cond(el_current):
            list[to_idx] = el_current
            to_idx += 1
    del list[to_idx:]

big_list = [1, 2, 7, 4, 6]

def main():
    my_list = [11, 1, 9, 3,  5, 2, 2, 7, 5, 5]
    contained_in_big = lambda el: el in big_list
    #Method 1
    filter_list(my_list, contained_in_big)
    #Method 2
    #my_list = [ x for x in my_list if contained_in_big(x)]
    #Method 3
    #my_list = filter(contained_in_big, my_list)

    print my_list

if __name__ == "__main__":
    main()

No comments:

Post a Comment