How to Check If an Argument Is Empty in Python

In Python, understanding how to check if an argument is empty is essential because it allows us to write more robust and error-proof code. In this tutorial, we’ll look at how to verify if an argument, data, value, variable, or object is empty.

Step 1: Understanding ’empty’ in Python

In Python, an argument is considered ’empty’ if it holds no value, or essentially, if it contains a False boolean value. This could take the form of an empty string, an empty list, an empty dictionary, a ‘None’ value, an empty set, or even a zero.

Each one of these values is considered False in Python when converted to a boolean context.

Step 2: The ‘if not’ statement

The most straightforward method of checking if an argument is empty in Python is to use an ‘if not’ statement. This check can be used for all types of objects whose boolean evaluation can result in False. Let’s take an example:

The Python code:

The output:

Step 3: The len() function

Besides the ‘if not’ statement, we can use the len() function which returns the number of elements in an object. We use the len() function with an ‘if’ statement to check if the length of the object is zero.

The Python code:

The output:

Step 4: The bool() function

The last method we’ll discuss in this tutorial is the use of Python’s bool() function. The bool() function converts a value to Boolean (True or False) using the standard truth testing procedure.

The Python code:

The output:

Conclusion

In this tutorial, we have demonstrated three different methods on how to check whether an argument is empty in Python. Take note that the choice of method can depend on the type of object you are working with.

Remember that in Python, a value or argument is considered ’empty’ if it holds a False boolean value.