Removing None objects from a sequence

Scott David Daniels Scott.Daniels at Acm.Org
Mon Dec 15 20:46:27 CET 2008


Steven D'Aprano wrote:
> On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote:
> ...
>> Tim Chase wrote:
>>>> If you want to literally remove None objects from a list....(or
>>>> mutable sequence)
>>>>
>>>> def deNone(alist):
>>>>    n=len(alist)
>>>>    i=j=0
>>>>    while i < n:
>>>>      if alist[i] is not None:
>>>>        alist[j] = alist[i]
>>>>        j += 1
>>>>      i += 1
>>>>    alist[j:i] = []
> Contrast that with the alternative suggested by Tim:
> 
> def deNone2(alist):
>     alist[:] = [x for x in alist if x is not None]
>  ...
> Here's another low-level algorithm, the classical delete items in place 
> algorithm. Three lines, one index, lousy O(N**2) performance.
> 
> def deNone3(alist):
>     for i in xrange(len(alist)-1, -1, -1):
>         if alist[i] is None:
>             del alist[i]
> 
> Now, let's do a shoot-out. Do they return the same thing?
    ... [good measurements generally reinforcing Tim's implementation] ...

If you want to keep the original's method, but do it in a more Pythonic
way, I would suggest:

     def deNone4(alist):
         j = 0
         for val in alist:
             if val is not None:
                 alist[j] = val
                 j += 1
         del alist[j :]

This still loses to Tim's clearer code, but by nowhere near as much.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list