create boolean

Steve Holden steve at holdenweb.com
Mon Mar 9 04:27:09 EDT 2009


Lie Ryan wrote:
> Fencer wrote:
>> Hi, I need a boolean b to be true if the variable n is not None and
>> not an empty list, otherwise b should be false.
>> I ended up with:
>> b = n is not None and not not n
>> which seems to work but is that normally how you would do it?
>> It can be assumed that n is always None or a list that might be empty
>>
>> - Fencer
> 
> The literal translation of that would be:
> 
> if n is not None and n != []:
>     b = True
> else:
>     b = False
> 
> it is a bit verbose, so one might want to find something shorter
> 
> b = True if n is not None and n != [] else False
> 
> I always feel if and in-line if to be easier and more readable than
> short-circuited operations.

So, in what significant way does this differ from

  b = n is not None and n != []

? Just for kicks, let's take a look at that:

# py2.2+ ... not py3 ?1.5.2? ?1.4?
print "%7s %7s %7s %7s %7s %7s" % (
  "a", "b", "bool(a)", "bool(b)", "formula1", "formula2")

formula1 = "True if n is not None and n != [] else False"
formula2 = "n is not None and n != []"
print 64 * "-"

for a in None, [], 0, 33, "",  "banana", {}, {1: 'one'}:
    for b in "-":
        n = a
        print "%7s %7s %7s %7s %7s %7s" % (
            a, b, bool(a), bool(b),
            eval(formula1), eval(formula2))

Those who run the program may see the results. I hope the small attached
graphic will be acceptable to them so those with no interpreter handy
may also see the results. If you do have an interpreter you are, of
course, free to vary the formulae, or add more for comparison.

regards
 Steve

PS: Indeed b *is* completely redundant. I just adapted a program I had
lying around ...
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
Holden Web LLC                 http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: bool.png
Type: image/png
Size: 22369 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090309/3e7ef604/attachment.png>


More information about the Python-list mailing list