Cleaning up conditionals

Deborah Swanson python at deborahswanson.net
Fri Dec 30 22:52:22 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>

Another neat thing to know, and yes, that's much more readable. I've run
into trouble testing for empty (tests failed when they shouldn't have),
but I can't remember where I've had that problem, and since it happened
early in my learning python, chances are pretty good I screwed something
else up.  Thanks, I'll remember to try using it again  and see if I can
get it right.
 




More information about the Python-list mailing list