リスト内包表記を使って次のように簡単に書けます。
[x for x in a_list if x]
↑は組み込み関数filter
を使って次のようにも書けますが、
pylint
で警告が出るのであまり使わないようにしてます。
filter(None, a_list):
Noneは除きたいけど0は保持したい場合は
[x for x in a_list if x is not None]
例
>>> a_list = [None, 'a', 'b', None, 'c', 0, 'd'] >>> print [item for item in a_list if item] ['a', 'b', 'c', 'd'] >>> print [item for item in a_list if item is not None] ['a', 'b', 'c', 0, 'd']
また、タイトルの内容からは逸れるけど
リスト内包表記はfor
とif
の順番を変えるとif ... else
も使えるようです。
>>> print [x if x is not None else u'EMPTY' for x in a_list] [u'EMPTY', 'a', 'b', u'EMPTY', 'c', 0, 'd']
リファレンス
python - remove None value from a list without removing the 0 value - Stack Overflow