Removing null items

Andrew M. Kuchling akuchlin at mems-exchange.org
Tue Nov 30 20:40:36 CET 1999


sragsdale at my-deja.com 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.

--amk




More information about the Python-list mailing list