使用这 3 个简单的技巧在 Python 中检查列表是否为空

以不同的方式检查列表是否为空。

在 Python 中有多种方法可以检查列表是否为空。 让我们一一看看。

长度

我们可以使用列表的长度来检查列表是否为空。 这是一个简单的解决方案,大多数人将其作为第一种方法。 让我们看看检查列表是否为空的步骤。

  • 编写一个名为 is_list_empty 的函数,它接受一个列表作为参数。
  • 检查列表的长度。
    • 如果长度为 0,则返回 True,否则返回 False。

而已。 我们完成了程序中涉及的步骤。

让我们的代码。

# function to check whether the list is empty or not
def is_list_empty(list):
    # checking the length
    if len(list) == 0:
        # returning true as length is 0
        return True
    # returning false as length is greater than 0
    return False

让我们用下面的代码检查我们的功能。

list_one = [1, 2, 3]
list_two = []
print(is_list_empty(list_one))
print(is_list_empty(list_two))

如果执行上面的代码,您将得到以下结果。

False
True

布尔值

空列表的布尔值始终为 False。 在这里,我们将利用 bool 方法。 我们将使用 bool 转换方法来检查列表是否为空。 让我们看看其中涉及的步骤。

  • 编写一个名为 is_list_empty 的函数,它接受一个列表作为参数。
  • 使用 bool 方法将列表转换为布尔值。
  • 反转结果并返回它。

是的! 而已。 我们完成了这些步骤。 让我们看看代码。

# function to check whether the list is empty or not
def is_list_empty(list):
    # returning boolean value of current list
    # empty list bool value is False
    # non-empty list boolea value is True
    return not bool(list)

让我们用下面的代码测试我们的功能。

list_one = [1, 2, 3]
list_two = []
print(is_list_empty(list_one))
print(is_list_empty(list_two))

您将获得与我们在前面的示例中看到的相同的输出。 执行并测试它。

  如何在 Minecraft 中制作兵马俑

相等运算符

还有另一种检查列表是否为空的简单方法。 我们可以直接将列表与空列表进行比较([]). 如果给定列表与空列表匹配,Python 返回 True。

让我们看看使用相等运算符检查列表是否为空的步骤。

  • 编写一个名为 is_list_empty 的函数,它接受一个列表作为参数。
  • 将给定列表与 [] 并返回列表。

一个简单的步骤让您在 Python 中受益匪浅。 让我们看看代码。

# function to check whether the list is empty or not
def is_list_empty(list):
    # comparing the list with []
    # and returning the result
    return list == []

现在,您可以检查我们在本教程中使用的带有代码片段的功能。 您将获得与以前相同的输出。

结论

这足以让开发人员检查列表是否为空。

可能还有其他方法可以检查列表是否为空。 我们已经看到了其中的一些。 选择最适合您的方法。

有兴趣掌握 Python 吗? 看看这个 课程.

快乐编码🙂

喜欢阅读这篇文章吗? 与世界分享怎么样?