If a variable is empty Python | Example code

You can Use bool() to check if a variable is empty in Python. Or you can also use if not statement to check it.

How to check if a variable is empty in Python Example

Simple python example code. Print True if the variable has a non-empty value, and False otherwise. Empty values include empty sequences, the integer 0, and the None value.

var1 = ''
var2 = {}
var3 = [1, 2, 3]
var4 = None

print(bool(var1))
print(bool(var2))
print(bool(var3))
print(bool(var4))

Output:

If variable is empty Python

Check empty variable with if not statement

bool is used implicitly when evaluating an object in a condition like an if or while statement, conditional expression, or a boolean operator.

Just use not keyword:

var1 = ''
if not var1:
    print("Variable is empty")

Output: Variable is empty

Do comment if you have any doubts and suggestions on this Python variable topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.