더북(TheBook)

Note ≡ 진리성(truthiness)의 특별한 경우


빠르게 설명하면 0과 동일한 숫자는 모두 거짓입니다. 그렇기 때문에 비어 있는 컬렉션과 길이가 0인 문자열도 거짓으로 판단할 수 있으며, FalseNone 싱글턴(singleton)도 마찬가지입니다. 따라서 이러한 값들은 ‘불리언 논리의 맥락’에서 보면 실제로 False와 동일하며, 나머지 객체들은 모두 참에 해당합니다.

참이나 거짓 어디에도 해당하지 않는 객체 중에 잘 알려진 것은 NumPy의 배열, Pandas의 Series, DataFrame이 있습니다.

>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1, 2])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> series = pd.Series([1, 2], index=["A", "B"])
>>> series
A    1
B    2
dtype: int64
>>> bool(series)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.