Last modified: November 10, 2020

How to Properly Check if a Variable is Empty in Python

In this tutorial, we'll learn how to check if a variable if is empty by using 2 ways, the good and the bad ways.

1. Checking if variable is empty [Good way]

In this example, we'll check if the variable var is empty.


#empty variable
var = ""

#check if variable is empty
if not var:
    print("yes it is!")
    

output

yes it is!

as you can see, var is empty

2. Checking if variable is empty [Bad way]

In this example, we will do the same thing that we did in the first example, but now in the bad way.


#empty variable
var = ""

#check if variable is empty
if len(var) == 0:
    print("yes it is!")

    

output

yes it is!

As you can see, the code is working very well, but this is the worst way, because we don't need the len function,
remind, your code should be short, clean and easy to read



Conclusion

In this article, we have learned how to check empty variables, if you want to check empty variables, list and tuple, you should do like we did in the fist example.