<tutorialjinni.com/>

Python check if variable is not null or empty

Posted Under: Programming, Python, Tutorials on Nov 4, 2024
Python check if variable is not null or empty
In Python, to check if a variable is not None and is not an empty string (or an empty data structure like a list or dictionary), you can use an if statement with both conditions. Here’s a common way to do it:
if my_variable is not None and my_variable != "":
    # Do something if my_variable is not None and not empty
Or, if you want a more general approach to check if my_variable is not None, not empty, and also covers lists, dictionaries, or other containers, you can use:
if my_variable:
    # Do something if my_variable is not None and not empty
This works because an empty string (""), an empty list ([]), and an empty dictionary ({}) all evaluate to False in Python. However, if you only want to check for None or an empty string specifically, use the first example.


imgae