What way is the best to check an empty list?

Carl Banks pavlovevidence at gmail.com
Thu Mar 26 00:43:16 CET 2009


On Mar 25, 7:38 am, srinivasan srinivas <sri_anna... at yahoo.co.in>
wrote:
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:

PEP 8 recommends the last one, and most Pythonistas here probably
would as well, so that is probably what you should do if you don't
otherwise have an opinion.  I have an opinion, so I use "len(A) == 0"
in projects I control.

However, if this object is intended to be an list of numbers, and if
the application does any sort of mathematical calculations, then I
recommend you use the "len(A) == 0" test and no other.  This is to
allow interaction with numpy, which doesn't work with the "if not A"
test.


Carl Banks



More information about the Python-list mailing list