Python 程序检查列表是否为空

编写一个 Python 程序来检查列表是否为空。有三种方法可以检查列表是否为空:使用内置的 len() 函数、not 运算符以及在 if 语句中直接与 [] 进行比较。

使用 not 运算符

我们使用 not 运算符来查找列表是否为空列表。

list1 = []

if not list1:
    print("The List is Empty")
else:
    print("The List is Not Empty")
Program to Check List Is Empty or Not

使用 len 检查列表是否为空的 Python 程序

我们在此示例中使用了 len 函数,该函数返回列表的长度。如果列表长度等于零,则列表为空;否则,列表不为空。

list1 = []

if len(list1) == 0:
    print("Empty")
else:
    print("Not Empty")
Empty

直接比较

除了上述方法,您还可以直接将列表与 [] 进行比较,以查找列表是否为空。

ls = []

if ls == []:
    print("True")
else:
    print("False")
True