Python Check if a List is Empty

Python3 Examples

In Python, it is very simple to check whether a list is empty. We can directly use theifstatement to check whether the length of the list is 0, or directly check whether the list itself isFalse。

Example

my_list = []

# Method 1: Check whether the length of the list is 0
if len(my_list) == 0:
    print("The list is empty")
else:
    print("The list is not empty")

# Method 2: Directly check whether the list is False
if not my_list:
    print("The list is empty")
else:
    print("The list is not empty")

Code explanation:

  1. len(my_list) == 0:len()The function returns the length of the list. If the length is 0, the list is empty.
  2. not my_list: In Python, an empty list is consideredFalse, thereforenot my_listwill return when the list is emptyTrue。

Output result:

Empty list

Both methods can effectively determine whether a list is empty. Which method to choose depends on personal preference.

Python3 Examples

Other extensions