How to Check if a List, Dict or Set is Empty in Python as per PEP8
The aim of this how-to-guide🏁 is to demo checking for empty list in Python as per PEP8 (Style Guide) — I know this is trite/repetitive yet it is still counter-intuitive to me when I encounter this in code of others.
2 min readSep 7, 2023
The way to go is to simply write “if <object>” which in general performs four checks in Python
- Following Built-in Types — Python 3.9.7 documentation you check 4 things when you write
if <object>:
Null
- Empty
False
- Zero (
0
)
- if it is a collection, it is mainly for emptiness, though
l = [0]
of course passes the test and is different froml=[]
Again, for sequences, (strings / lists / tuples), use the fact that empty sequences are false
#Yes:
if not seq:
if seq:
#No:
if len(seq):
if not len(seq):
— from PEP8
- not just sequences, all collections apply, i.e. do this also for dicts and sets
>>> a = {}
>>> if not a: print("empty")
empty
on duck-typing vs “explicit is better than implicit”
- from stack_overflow_question_53513
- there is a trade-off between explicitness and type flexibility
- being explicit means not doing “magical” things.
- duck typing means relying on general/conventional interfaces → rather than explicitly checking for types → you could argue that conventional interfaces are not magical, right
- so something like
if a == []
is forcing a particular type (() == []
isFalse
). - here, general consensus seems to be that duck typing wins out
- in effect, it is saying that
__nonzero__
is the interface for testing emptiness (__bool__
in python 3 → built-inbool()
) - see https://docs.python.org/3/reference/datamodel.html#object.__bool__
>>> a = []
>>> bool(a)
False
>>> a = [1]
>>> bool(a)
True
compare: how things are done in C, also from SO
The canonical way of knowing if an array in C is empty is by dereferencing the first element and seeing if it is null, assuming an array that is nul-terminated. Otherwise, comparing its length to zero is utterly inefficient if the array is of a significant size. Also, typically, you would not allocate memory for an empty array (pointer remains null), so it makes no sense to attempt to get its length. I am not saying that len(a) == 0 is not a good way of doing it, it just does not scream 'C' to me when I see it.