Removing None objects from a sequence

Tim Chase python.list at tim.thechases.com
Fri Dec 12 17:32:08 EST 2008


> 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] = []
> 
> blist=[None,1,None,2,None,3,None,None,4,None]
> deNone(blist)
> print(blist)
> 
> # prints [1, 2, 3, 4]

...wouldn't a cleaner way of doing this just be

   >>> blist=[None,1,None,2,None,3,None,None,4,None]
   >>> alist = blist
   >>> blist[:] = [x for x in blist if x is not None]
   >>> blist
   [1, 2, 3, 4]
   >>> alist
   [1, 2, 3, 4]

By using the slice assignment, it leaves the blist referring to 
the same list-object (as shown by the "alist" bit), and modifying 
it in place.  This reads a lot more cleanly in my estimation.

If the data-set is large, in 2.5+, you can just use a generator:

   blist[:] = (x for x in blist if x is not None)

-tkc






More information about the Python-list mailing list