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 :set('casa') & set('porca')
In :set('casa') | set('porca')
Out:set(['a', 'c', 'o', 'p', 's', 'r'])
and they work correctly. Now, what is confusing, is that if you do:
In :set('casa') and set('porca')
Out:set(['a', 'p', 'c', 'r', 'o'])
In :set('casa') or set('porca')
Out:set(['a', 'c', 's'])
The results are not what you would expect from an AND or OR operation, from the mathematical point of view! apparently the "and" operation is returning the the second set, and the "or" operation is returning the first.
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? My answer, as many readers have also pointed out , is that sets are implemented like this, so that they can be used in the "and/or trick" or ternary operator. But this is very confusing for users that are thinking about sets in a mathematical way, where "AND" means intersection and "OR" means union. I can see this confusing many newbies...