Cleaning up conditionals
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.
# 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 zip.com.au>
More information about the Python-list