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:
def is_empty(any_structure): if any_structure: print('Structure is not empty.') return False else: print('Structure is empty.') return True
- Python Programming – Tuple Functions
- Python Programming – Creation, Initialization and Accessing The Elements In A Dictionary
- Python Programming – Built-in Functions
It will magically detect if any built in structure is empty. So if we run this:
>>> 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
Then, if we add something to each:
>>> d['element'] = 42 >>> l.append('element') >>> ms.add('element') >>> s = 'string' >>> t = ('element')
And we check each one again, this will be the result:
>>>is_empty(d) Structure is not empty. False
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:
>>> d = {None:'value'} >>> is_empty(d) Structure is not empty. False
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:
if len(l) == 0: print('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.