dackdive's blog

新米webエンジニアによる技術ブログ。JavaScript(React), Salesforce, Python など

[python]リストからNoneを除外する簡単な書き方

リスト内包表記を使って次のように簡単に書けます。

[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']

また、タイトルの内容からは逸れるけど
リスト内包表記はforifの順番を変えると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

soyogu: Python 内包表記 if else