【Python】’if element not in List’と書きましょう

Python
この記事は約2分で読めます。

Pythonでリスト内に要素があるか確認するには
in演算子を使用します。

 

リスト内に要素がないかどうか調べるときは
not演算子とin演算子を組み合わせます。

 

if not 6 in numbersとif 6 not in numbersですが
動作に違いはありません。

しかし最初のif文ではPyCharmなどのIDEでPEP 8の違反Warningが出ます。

なぜ、’not element in List’と書くと良くないか検索したところ
Stack Overflowで回答を見つけました。

Python `if x is not None` or `if not x is None`?
I've always thought of the if not x is None version to be more clear, but Google's style guide and PEP-8 both use if x is not None. Are there any minor performa...

こちらで答えているDaniel Stutzbachさんの答えが分かりやすいです。

Stylistically, I try to avoid not x is y.
Although the compiler will always treat it as not (x is y),
a human reader might misunderstand the construct as (not x) is y.
If I write x is not y then there is no ambiguity.

さきほどのPEP 8が出ている違反コードは
‘if not 6 in numbers’と6ではないものがnumbersにあるか?と
誤って読まれる可能性があるということですね。

‘if 6 not in numbers’は、6がnumbersに存在しないよね?ということを
明確にif文の条件としているので、曖昧さを排除した書き方になってます。

よく’if not element in list’と書いては、IDEにPEP8違反を指摘されて直しているので
次回から気をつけたいと思います。

コメント