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

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

1numbers = [1, 2, 3, 4, 5]
2
3if 1 in numbers:
4    print('1はあります。')

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

1numbers = [1, 2, 3, 4, 5]
2
3if not 6 in numbers: #PEP8違反
4    print('6はありません。')
5
6if 6 not in numbers: #PEP8違反じゃない
7    print('6はありません。')

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? [closed]

こちらで答えている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違反を指摘されて直しているので次回から気をつけたいと思います。

関連ページ