リストに値が入っているか、いないかの判定でlen()を使って判定することもできるが、これだとスマートじゃない。
sample.py
list_1 = []
if len(list_1) > 0:
print("list_1 : Not empty")
else:
print("list_1 : empty")
もっと簡潔にかける方法あり、それは以下。
sample.py
list_1 = [] # 空のリストを用意
if list_1:
print("list_1 : Not empty :", list_1)
else:
print("list_1 : empty")
list_1.append(1) # 空のリストへ値を追加
if list_1:
print("list_1 : Not empty :", list_1)
else:
print("list_1 : empty")
# 出力結果
# list_1 : empty
# list_1 : Not empty : [1]
上記のif list_1: は「もし何か値が入っていればTrue」の意味。とても便利。
また、if文によるTrue or False の判定は以下のようになる。タプル、リスト、ディクショナリ型は同じように判定できる。
sample.py
empty_1 = ''
empty_2 = ' '
empty_3 = 0
empty_4 = 1
empty_5 = "Hello"
if empty_1:
print(" "" : Not empty")
else:
print(" '' : empty")
if empty_2:
print(" ' ' : Not empty")
else:
print(" ' ' : empty")
if empty_3:
print(" 0 : Not empty")
else:
print(" 0 : empty")
if empty_4:
print(" 1 : Not empty")
else:
print(" 1 : empty")
if empty_5:
print(" Hello : Not empty")
else:
print(" Hello : empty")
# 出力結果
# '' : empty
# ' ' : Not empty
# 0 : empty
# 1 : Not empty
# Hello : Not empty
以上