boolean operations on sets

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Aug 7 03:46:38 EDT 2007


Flavio a écrit :
> Hi, I have been playing with set operations lately and came across a
> kind of surprising result given that it is not mentioned in the
> standard Python tutorial:
> 
> with python sets,   intersections  and unions are supposed to be done
> like this:
> In [7]:set('casa') & set('porca')
> Out[7]:set(['a', 'c'])
> 
> In [8]:set('casa') | set('porca')
> Out[8]:set(['a', 'c', 'o', 'p', 's', 'r'])
> 
> and they work correctly. Now what is confusing is that if you do:
> 
> In [5]:set('casa') and set('porca')
> Out[5]:set(['a', 'p', 'c', 'r', 'o'])
> 
> In [6]:set('casa') or set('porca')
> Out[6]:set(['a', 'c', 's'])
> 
> The results are not what you would expect from an AND  or OR
> operation, from the mathematical point of view! aparently the "and"
> operation is returning the the second set, and the "or" operation is
> returning the first.

the semantic of 'and' and 'or' operators in Python is well defined and 
works the same for all types AFAIK.

> If python developers wanted these operations to reflect the
> traditional (Python) truth value for data structures: False for empty
> data structures and True otherwise, why not return simply True or
> False?
>
> So My question is: Why has this been implemented in this way? 

Because Python long lived without the 'bool' type - considering None, 
numeric zero, empty string and empty containers as false (ie : 
'nothing', and anything else as true (ie : 'something').

> I can
> see this confusing many newbies...

Yes, and this has been one of the arguments against the introduction of 
the bool type. Changing this behaviour would have break lot of existing 
code, and indeed, not changing it makes things confusing.

OTHO - and while I agree that there may be cases of useless complexities 
in Python -, stripping a language from anything that might confuse a 
newbie doesn't make great languages.



More information about the Python-list mailing list