Pythonでは、リストが空かどうかを判断する方法がいくつかあります。以下にその方法を紹介します。
空のリストの判定方法
方法1: if not
文を使用する
Pythonのリストは、空であれば False
、中身が入っていれば True
を返す性質があります。この性質を利用して、リストが空かどうかを判断することができます。
list_fruits = ["Apple", "Banana", "Orange"]
list_empty = []
if not list_fruits:
print("list is empty")
else:
print("list is not empty") # list is not empty
if not list_empty:
print("list is empty") # list is empty
else:
print("list is not empty")
方法2: len
関数を使用する
len
関数を用いても、リストが空かどうかを判断することができます。ただし、Pythonのコーディング規約のPEP 8では非推奨とされています。
list_fruits = ["Apple", "Banana", "Orange"]
list_empty = []
if len(list_fruits) == 0:
print("list is empty")
else:
print("list is not empty") # list is not empty
if len(list_empty) == 0:
print("list is empty") # list is empty
else:
print("list is not empty")
方法3: 空のリストと比較する
空のリストとの比較を行っても、リストが空かどうかを判断することができます。ただし、こちらの方法もPEP 8では非推奨とされています。
list_fruits = ["Apple", "Banana", "Orange"]
list_empty = []
if list_fruits == []:
print("list is empty")
else:
print("list is not empty") # list is not empty
if list_empty == []:
print("list is empty") # list is empty
else:
print("list is not empty")
空のリストの作成方法
Pythonでは、空のリストを作成する方法がいくつかあります。以下にその方法を紹介します。
方法1: []
で作成する
list_empty = []
print(list_empty) # []
print(len(list_empty)) # 0
方法2: list
関数を使用する
list_empty = list()
print(list_empty) # []
print(len(list_empty)) # 0
以上がPythonでの空リストの扱い方になります。これらの知識を活用して、Pythonプログラミングをより効率的に行いましょう。