Cleaning up conditionals

Cameron Simpson cs at zip.com.au
Fri Dec 30 20:59:30 EST 2016


On 30Dec2016 15:17, Deborah Swanson <python at deborahswanson.net> 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 ix.netcom.com    HTTP://wlfraed.home.netcom.com/
>
>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.

So:

  if a:
    # a is not empty: len(a) > 0
  else:
    # 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.

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list