Skip to content

If a variable is empty Python | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *