Skip to content Skip to sidebar Skip to footer

Remove Items From A List While Iterating Without Using Extra Memory In Python

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 l

Solution 1:

li = [ x for x in li if condition(x)]

and also

li = filter(condition,li) 

Thanks to Dave Kirby

Solution 2:

Here is an alternative answer for if you absolutely have to remove the items from the original list, and you do not have enough memory to make a copy - move the items down the list yourself:

def walk_list(list_of_g):
    to_idx =0for g_current in list_of_g:
        ifnotsubtle_condition(g_current):
            list_of_g[to_idx] = g_current
            to_idx += 1
    del list_of_g[to_idx:]

This will move each item (actually a pointer to each item) exactly once, so will be O(N). The del statement at the end of the function will remove any unwanted items at the end of the list, and I think Python is intelligent enough to resize the list without allocating memory for a new copy of the list.

Solution 3:

removing items from a list is expensive, since python has to copy all the items above g_index down one place. If the number of items you want to remove is proportional to the length of the list N, then your algorithm is going to be O(N**2). If the list is long enough to fill your RAM then you will be waiting a very long time for it to complete.

It is more efficient to create a filtered copy of the list, either using a list comprehension as Marcelo showed, or use the filter or itertools.ifilter functions:

g_list = filter(not_subtle_condition, g_list)

If you do not need to use the new list and only want to iterate over it once, then it is better to use ifilter since that will not create a second list:

forg_currentin itertools.ifilter(not_subtle_condtion, g_list):
    # do stuff with g_current

Solution 4:

The built-in filter function is made just to do this:

list_of_g = filter(lambda x: not subtle_condition(x), list_of_g)

Solution 5:

How about this?

[x for x in list_of_g if not subtle_condition(x)]

its return the new list with exception from subtle_condition

Post a Comment for "Remove Items From A List While Iterating Without Using Extra Memory In Python"