Cleaning up conditionals

MRAB python at mrabarnett.plus.com
Fri Dec 30 22:51:33 EST 2016


On 2016-12-31 01:59, Cameron Simpson wrote:
> 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.
>
[snip]

For Python 2, it tries __nonzero__, or __len__ if that fails.

For Python 3, it tries __bool__, or __len__ if that fails.



More information about the Python-list mailing list