添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
坚韧的稀饭  ·  How to fix ...·  2 天前    · 
傻傻的课本  ·  Python 教程 — Python ...·  昨天    · 
英姿勃勃的火柴  ·  PEP 0 – Index of ...·  昨天    · 
开朗的茄子  ·  Spark - RCC User Guide·  昨天    · 
内向的花卷  ·  华为MateBook GT ...·  1 月前    · 
玩篮球的灯泡  ·  c++ pdf reader ...·  9 月前    · 

Table of Contents

7 Ways to Check if a List is Empty

In this section, we will explore 5 ways to check if a list is empty in Python .

Specifically, we will go over the following methods:

# Using bool() function to check emptiness if not bool(my_list): print("The list is empty.") # else block else: print("The list is not empty.")

The following output will be displayed in the console:

# Using len() function to check emptiness if len(my_list) == 0: print("The list is empty.") else: print("The list is not empty.")

In this example, the output will be “The list is empty.” because my_list doesn’t contain any elements.

my_list = [0, False, "", None]  # A list with falsy values
# Using filter() function to check for emptiness based on truthiness
filtered_list = list(filter(lambda x: x, my_list))
if not filtered_list:
    print("The list is empty or contains only falsy values.")
else:
    print("The list is not empty.")

In this example, we have some constants defined in my_list. The output will be “The list is empty or contains only falsy values.”, because while my_list does have elements, all of them are considered false values.

# Using set comparison to check for emptiness if set(my_list) == set(): print("The list is empty.") else: print("The list is not empty.")

In this example, the output will be “The list is empty.” because my_list does not contain any elements.

def is_empty(lst):
    """Return True if the list is empty, otherwise return False."""
    return not lst
my_list = []
# Using the custom function to check for emptiness
if is_empty(my_list):
    print("The list is empty.")
else:
    print("The list is not empty.")

In this example, the custom function is_empty checks the truthiness of the list and returns the result.

The output will be “The list is empty.” because my_list doesn’t have any elements.