[파이썬, Python] if x is not None or if not x is None?


질문: 파이썬에서 `if x is not None`와 `if not x is None` 중에서 어떤 표현이 맞을까요?

정답: 둘은 같다. 하지만, `if x is not None`를 사용하는 것이 좋겠다.


다음의 예제를 보자.


>>> x=2

>>> x

2

>>> bool(x)

True

>>> not x

False

>>> x is not None

True

>>> not x is None

True

>>> not (x is None)

True

>>> (not x) is None

False


즉, 아래의 3가지 예제는 모두 동일한 표현입니다.

if x is not None

if not x is None

if x


소스를 읽는 사람의 입장에서 볼 때, `if not x is None`는 혼란을 줄 수 있는 방식이기 때문에...


시험 문제를 출제하는 것이 아니라면, 보는 사람이 읽기 쉬운 것이 더 좋겠죠 ^^

그리고, `if x is not None` 가 `if x`보다는 처리 속도가 약간 빠르다고 합니다.


결론적으로는, 어떤 것을 사용해도 무방하지만,

가급적 `if x is not None`를 사용하는 것이 좋겠습니다.




반응형

+ Recent posts