[Tutor] Removing Null Elements from a List

Tim Peters tim.one@home.com
Sat, 10 Mar 2001 15:11:15 -0500


[Britt Green]
> If I have a list that looks like:
>
> [None, None, None, None, None, None, None, None, None, None,
>  ['/atl/horseradishgrill_1'], None, None, None, None, None, None,
>  None, None,  None, None, None, None, None, None, None, None, None,
>  None, ['/boston/archive'], None, None, None, ['/boston/cafe_fleuri'],
>  None, None, None, None, None, None, None, None, None, None,
>  ['/boston/rplace'], ['/boston/salamander'], None, ['/boston/test'],
>  ['/boston/the_federalist'], None, ['/boston/yanks']]
>
> How can I remove those None elements in it?
> ...

[Daniel Yoo]
> One way to do this is to use the functional tool filter():
>
> ###
> def isTrue(x):
>     if x: return 1
>     else: return 0
>
> cleanFiles = filter(isTrue, files)
> ###
>
> That's one way of removing all the None's out of there: isTrue() is a
> function that says 1 only when the filename is either nonempty or not
> None.

First note that isTrue is the same as operator.truth:

>>> import operator
>>> print operator.truth.__doc__
truth(a) -- Return 1 if a is true, and 0 otherwise.
>>> filter(operator.truth, ["", "a", None, ["b"], 0.0])
['a', ['b']]
>>>

Then note that filter supports a little-known special case:

>>> print filter.__doc__
filter(function, sequence) -> list

Return a list containing those items of sequence for which function(item)
is true.  If function is None, return a list of items that are true.
>>> filter(None, ["", "a", None, ["b"], 0.0])
['a', ['b']]
>>>

So filter(None, list) works for this without further ado, and happens to be
very fast.