示例 1:使用布尔运算
my_list = []
if not my_list:
print("the list is empty")
输出
the list is empty
如果 my_list
为空,那么 not
返回 True。
这是测试空列表最 pythonic 的方式。如果您想了解更多关于布尔真值的信息,可以参考真值测试。
示例 2:使用 len()
my_list = []
if not len(my_list):
print("the list is empty")
输出
the list is empty
在此示例中,使用列表的长度来检查列表中是否有任何元素。如果列表的长度为 0,则该列表为空。
要了解更多信息,请访问 Python len()。
示例 3:与 [] 比较
my_list = []
if my_list == []:
print("The list is empty")
输出
The list is empty
[]
是一个空列表,因此如果 my_list
没有元素,那么它应该等于 []
。