"
This article is part of in the series
Published: Tuesday 19th March 2013
Last Updated: Wednesday 29th December 2021

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:

[python]
def is_empty(any_structure):
if any_structure:
print('Structure is not empty.')
return False
else:
print('Structure is empty.')
return True
[/python]

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

[python]
>>> d = {} # Empty dictionary
>>> l = [] # Empty list
>>> ms = set() # Empty set
>>> s = '' # Empty string
>>> t = () # Empty tuple
>>> is_empty(d)
Structure is empty.
True
>>> is_empty(l)
Structure is empty.
True
>>> is_empty(ms)
Structure is empty.
True
>>> is_empty(d)
Structure is empty.
True
>>> is_empty(s)
Structure is empty.
True
>>> is_empty(t)
Structure is empty.
True
[/python]

Then, if we add something to each:

[python]
>>> d['element'] = 42
>>> l.append('element')
>>> ms.add('element')
>>> s = 'string'
>>> t = ('element')
[/python]

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

[python]
>>>is_empty(d)
Structure is not empty.
False
[/python]

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:

[python]
>>> d = {None:'value'}
>>> is_empty(d)
Structure is not empty.
False
[/python]

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:

[python]
if len(l) == 0:
print('Empty!')
[/python]

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

Joey Payne