1
2

More than 3 years have passed since last update.

値の”あり” 、”なし”を簡単に判定する基本テク

Last updated at Posted at 2019-12-24

リストに値が入っているか、いないかの判定で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

以上

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2