Removing from a List in Place

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Sep 5 19:51:49 EDT 2006


Tim Williams:
> You could also use a list comprehension for your case
> >>> alist = [1 ,2 ,3]
> >>> alist = [x for x in alist if x != 2]
> >>> alist
> [1, 3]

The list comprehension filtering is the simpler and often the best
solution. For memory-conscious people this is another possible
(un-pythonic) solution, usable in less dynamic languages too (not much
tested), expecially if the good elements are few (Psyco may help too).
I haven't tested its speed, but in Python it may be slower than the
simpler comprehension filtering solution:

array = [1,2,3,1,5,1,6,0]
good = lambda x: x > 2
slow = 0
for fast, item in enumerate(array):
    print item,
    if good(item):
        if slow != fast:
            array[slow] = array[fast]
        slow += 1
print "\n", array
del array[slow:]
print array

Output:
1 2 3 1 5 1 6 0
[3, 5, 6, 1, 5, 1, 6, 0]
[3, 5, 6]

Bye,
bearophile




More information about the Python-list mailing list