xor operator?

Hans Nowak ivnowa at hvision.nl
Fri Jan 26 10:56:19 EST 2001


On 26 Jan 01, Thomas Wouters wrote:

> > > In the specific Python
> > > sense, the return value of the boolean xor operation would also be
> > > vague.
> 
> > Simply 0 or 1 would be a possibility, but that is not what Python's
> > 'and' and 'or' do. So maybe, if it evaluates to true, it returns the
> > 'true' element; otherwise it returns 0 (like 'and' and 'or' do).
> 
> 'and' and 'or' never return '0'. They always return one of their elements,
> that's what makes them so useful (in my eyes :) xor doesn't have that 

Hm, I see what you mean:

>>> (2==1) and (4>5)
0
>>> 3 and []
[]

I originally come from a Pascal-ish background, and in that language a 
boolean expression always returns a Boolean, so either True or False, but 
not something else. I guess it's in the nature of the language.

I found Python's behavior very confusing at first -- 'and' and 'or' that 
return something else than 0 and 1? I've come to like it now, but 
apparently haven't fathomed everything of it.

> > Can't speak for him, but I always wondered why the xor was missing, too.
> > It simply belongs there next to the and/&, or/| pairs. :)
> 
> Well, that might be, but like I said, none of the languages I know have a
> boolean xor operator. If you really really want it, you can use
> 
> (not not x)^(not not y)
> 
> which is just about as obvious as 'x xor y'. 

I never needed it myself; I have just been wondering why it wasn't there. 
Same thing for C, by the way.

> I'm not really explaining why it isn't there, because I don't know, I'm just
> explaining why not many people care :) The chance of getting it now, though,
> is very slim. 'and' and 'or' are keywords, and 'xor', as an operator, would
> have to be, too. Introducing keywords can break a lot of code :P

We might slip in this keyword when the string module will be removed. 
Everyone's code will then be broken anyway, so people will hardly notice. 
;-)


--Hans Nowak (ivnowa at hvision.nl)
Info Vision Europe BV




More information about the Python-list mailing list