The preferred way to check if any list, dictionary, set, string or tuple is empty in Python is to simply use an if statement to check it.

For example, if we define a function as such:

It will magically detect if any built in structure is empty. So if we run this:

Then, if we add something to each:

And we check each one again, this will be the result:

As you can see, all the default data structures are detected as empty by treating the structure like a boolean in the if statement.

If the data structure is empty, it "returns" False when used in a boolean context. If the data structure has elements, it "returns" True when used in a boolean context.

One thing to note is that "empty" keys that have values in dictionaries will still be counted as "non-empty". For example:

This is because even though the key is "empty", it still counts as an entry in the dictionary, which means it's not empty.

"Is it really that simple? Do I have to do anything else?", I hear you say.

Yes, it is that simple. Python is amazing. Deal with it. :)

How NOT to Check if a List, Tuple, or Dictionary is Empty

"So what if I want to use a different way to check if these structures are empty?", you say.

Well, most other ways aren't "wrong", they're just not the Python way of doing things. For example, if you wanted to check if a structure was empty by using Python's len function, that would not be considered Pythonic.

For example, you could use this way to check if a list is empty:

Now, this is most certainly not wrong, but why would you type all that extra code? When something is labeled "Pythonic", it is usually referring to Python's nature of being very terse. So if you can save space by making your code shorter, that is usually the more Pythonic way of doing things.

The way above would probably be labeled as the "C" way of doing things, because it looks a lot like C code.

That's all for this article!

Until we meet again.

About The Author

  • Sara

    It is easier to do if any_structure: instead of defining that function.

  • Bernhard K√∂hler

    small correction:

    `t = ('element')`

    will create a string, not a tuple. You have to add a comma after the element in order to create a tuple.

    
    # a real tuple
    t = ('element',)