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 aandlen(a) == 0are 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
acan be anything. For example,a = None. The checknot ais fine, and will returnTrue. Butlen(a) == 0will not be fine at all. Instead you will getTypeError: object of type 'NoneType' has no len(). This is a totally valid option, but theifstatements 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:ais a sequence?ifstatement crashed on non-sequences?Remember that making the code look pretty takes second place to getting the job done correctly.