Zen of Python 'Explicit is better than implicit'

The two statements have very different semantics. Remember that Python is dynamically typed.

For the case where a = [], both not a and len(a) == 0 are equivalent. A valid alternative might be to check not len(a). In some cases, you may even want to check for both emptiness and listness by doing a == [].

But a can be anything. For example, a = None. The check not a is fine, and will return True. But len(a) == 0 will not be fine at all. Instead you will get TypeError: object of type 'NoneType' has no len(). This is a totally valid option, but the if 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:

  • Have you already verified whether a is a sequence?
  • Do you need to?
  • Do you mind if your if statement crashed on non-sequences?
  • Do you want to handle other falsy objects as if they were empty lists?

Remember that making the code look pretty takes second place to getting the job done correctly.

Tags:

Python

Pep