Removing null items

Andrew M. Kuchling akuchlin at
Tue Nov 30 14:40:36 EST 1999

sragsdale at writes:
> So I've got a very simple desire: to remove all false (I.E. None, 0, '',
> []) items from a list.

The filter() built-in function, when not passed a specific function,
does exactly this:

>>> filter(None, [ 1,2,0, None, [], '12', '' ])
[1, 2, '12']

filter(F, seq) returns all the elements of the sequence 'seq', for
which the function F returns true: for example, the following code 
takes all the strings of even length:

>>> filter(lambda s: len(s) % 2 == 0, ['a', 'ab', '', 'abcd'])
['ab', '', 'abcd']

If F is None, then filter() simply returns those elements that Python
treats as true.


More information about the Python-list mailing list