I'm trying to understand what 'implicit' and 'explicit' really means in the context of Python.
a = []
# my understanding is that this is implicit
if not a:
print("list is empty")
# my understanding is that this is explicit
if len(a) == 0:
print("list is empty")
I'm trying to follow the Zen of Python rules, but I'm curious to know if this applies in this situation or if I am over-thinking it?
The two statements have very different semantics. Remember that Python is dynamically typed.
For the case where
a = []
, bothnot a
andlen(a) == 0
are equivalent. A valid alternative might be to checknot len(a)
. In some cases, you may even want to check for both emptiness and listness by doinga == []
.But
a
can be anything. For example,a = None
. The checknot a
is fine, and will returnTrue
. Butlen(a) == 0
will not be fine at all. Instead you will getTypeError: object of type 'NoneType' has no len()
. This is a totally valid option, but theif
statements do very different things and you have to pick which one you want.(Almost) everything has a
__bool__
method in Python, but not everything has__len__
. You have to decide which one to use based on the situation. Things to consider are:a
is a sequence?if
statement crashed on non-sequences?Remember that making the code look pretty takes second place to getting the job done correctly.