Removing from a List in Place

Steve Holden steve at holdenweb.com
Wed Sep 6 09:58:41 CEST 2006


bearophileHUGS at lycos.com wrote:
> 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]
> 
This would be a way-premature optimisation until you had proven the need 
for it in the context of a specific program.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list