How is the logical processing being done for strings like 'Dog' and 'Cat'

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Oct 20 23:55:19 EDT 2008


On Mon, 20 Oct 2008 18:41:23 -0700, Sumitava Mukherjee wrote:

> What is python doing when we type in ('God' and 'Devil') or key in (01
> and 10) ?


There are two important things you need to know:

(1) All Python objects have a boolean context.

(2) Python's boolean operators are short-circuit operators.


Point (1) means that you can say this:


if x:
   print 'x has a true value'
else:
   print 'x has a false value'

and it will work for any x, not just True and False.

As a general rule, false values are empty:

- the empty string is false: ''
- empty lists are false: []
- empty tuples are false: ()
- zeroes are false: 0, 0.0
- None is false
- etc.

and everything else is true.

So you can do this:

if alist:
    # alist is not empty
    x = alist[0]  # so this is safe
else:
    print 'alist is empty'


config = get_config_parser()  # whatever that is...
if config:
   do_stuff_with_config
else:
   print "config is empty"




Point (2) means that Python will only evaluate the least number of 
objects needed. So for example:

42 or 19

Since 42 is a true object, looking at the second item is pointless, and 
Python short-circuits by returning 42.

0 or 19

Since 0 is a false object, Python must look at the second item. Since 19 
is true, it returns 19.

And similarly for and.


This is especially useful with the or operator. Instead of this:

astring = something()
if len(astring) == 0:
    astring = '<empty>'
do_something_with(astring)


you can do this:

astring = something() or '<empty>'
do_something_with(astring)



-- 
Steven



More information about the Python-list mailing list