Cleaning up conditionals

Cameron Simpson cs at
Fri Dec 30 20:59:30 EST 2016

On 30Dec2016 15:17, Deborah Swanson <python at> wrote:
>> 	Ever consider using conjunctions?
>> 	if len(l1[st]) and not len(l2[st]):
>> 		#0 is considered a false -- no need to test for "==0"
>> 		#non-0 is considered true -- no need to test for ">0"
>> 		#copy l1 to l2
>> 	elif not len(l1[st]) and len(l2[st]):
>> 		#copy l2 to l1
>> --
>> 	Wulfraed                 Dennis Lee Bieber         AF6VN
>>     wlfraed at    HTTP://
>That's a neat shortcut, len(a) instead of len(a)!= 0.  Thanks!

Also, for almost every python collection (lists, tuples, sets etc), python 
boolean logic tests __nonzero__, which works off len() by default.


  if a:
    # a is not empty: len(a) > 0
    # a is empty: len(a) == 0

I find this far more readable, presuming the reader knows that "empty" things 
test as false. Of course, you need to ensure that any "collection"-ish classes 
you use or write have this property, but the builtin ones do.

Cameron Simpson <cs at>

More information about the Python-list mailing list