SoFunction
Updated on 2025-03-04

Five ways to judge empty Python

1. Use if statement to judge

In Python, you can use the if statement to determine whether a variable is empty. If it is empty, you can perform the corresponding operation.

if var is None:
    print("var is empty!")
else:
    print("Var is not empty!")

The judgment here is whether var is None. If var is other null values, such as "" (empty string), [] (empty list), {} (empty dictionary), () (empty tuple), etc., you need to use the if not var statement to judge.

if not var:
    print("var is empty!")
else:
    print("Var is not empty!")

Here the not keyword is used to convert non-null values ​​into null values, and then use the if statement to make judgments.

2. Use the len() function to judge

In Python, you can use the len() function to get the length of the container (string, list, dictionary, tuple, etc.), and if the length is 0, the container is empty.

if len(var) == 0:
    print("var is empty!")
else:
    print("Var is not empty!")

The judgment here is based on whether the length is 0, so it applies not only to the None value, but also to other null values.

3. Use the not keyword to judge

In Python, you can use the not keyword to determine whether a variable is empty. This method is suitable for None, empty string, empty list, empty dictionary, empty tuple, etc.

if not var:
    print("var is empty!")
else:
    print("Var is not empty!")

4. Use the bool() function to judge

In Python, you can use the bool() function to convert a variable into a boolean value, and the null value will be converted to False.

if bool(var) == False:
    print("var is empty!")
else:
    print("Var is not empty!")

Note that it is necessary to determine whether bool(var) is equal to False, rather than directly determining whether bool(var) is equal to True.

5. Use try...except statement to judge

In Python, you can use the try...except statement to determine whether a variable is empty.

try:
    if var:
        print("Var is not empty!")
    else:
        print("var is empty!")
except:
    print("var is empty!")

Here the try statement is used to determine whether the variable is empty. If the variable is empty, the code in the except statement will be triggered.

6. Summary

The above introduces various methods for judging empty in Python, including if statements, len() function, not keywords, bool() function, try...except statements, etc. It should be noted that when using if statements and not keywords to judge, different null values ​​need to be written in different ways. For more relevant Python judging empty content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!