Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

missing 'xor' Boolean operator

27 views
Skip to first unread message

Dr. Phillip M. Feldman

unread,
Jul 14, 2009, 2:25:08 PM7/14/09
to pytho...@python.org

Current Boolean operators are 'and', 'or', and 'not'. It would be nice to
have an 'xor' operator as well.
--
View this message in context: http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24485116.html
Sent from the Python - python-list mailing list archive at Nabble.com.

Mark Dickinson

unread,
Jul 14, 2009, 2:47:41 PM7/14/09
to
On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>
wrote:

> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
> have an 'xor' operator as well.

Hmm. I don't think 'nice' is sufficient. You'd need to make the case
that it's sufficiently useful to justify adding a new keyword 'xor' to
the language; I suspect that would be an uphill struggle. :)

I'll just note that:

(1) It's easy to emulate xor: 'x xor y' <-> bool(x) != bool(y)

(2) 'and' and 'or' are special in that they have useful short-
circuiting behaviour; xor doesn't have this property (that is, you
always need to evaluate *both* operands to determine the result).

I'd also guess that 'xor' would be much less used than 'and' or 'or',
but maybe that's just a reflection of the sort of code that I tend to
write.

--
Mark

Chris Rebert

unread,
Jul 14, 2009, 3:43:42 PM7/14/09
to Mark Dickinson, pytho...@python.org
On Tue, Jul 14, 2009 at 11:47 AM, Mark Dickinson<dick...@gmail.com> wrote:
> On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>
> wrote:
>> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
>> have an 'xor' operator as well.
>
> Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
> that it's sufficiently useful to justify adding a new keyword 'xor' to
> the language;  I suspect that would be an uphill struggle. :)
>
> I'll just note that:
>
> (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)

Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)

Cheers,
Chris
--
http://blog.rebertia.com

Mark Dickinson

unread,
Jul 14, 2009, 3:52:34 PM7/14/09
to
On Jul 14, 8:43 pm, Chris Rebert <c...@rebertia.com> wrote:

> On Tue, Jul 14, 2009 at 11:47 AM, Mark Dickinson<dicki...@gmail.com> wrote:
> > (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)
>
> Using the xor bitwise operator is also an option:
> bool(x) ^ bool(y)

Good point. For some reason I expected bitwise operations on bools to
return ints rather than bools. Now I know better. :-)

Thanks,

Mark

Dr. Phillip M. Feldman

unread,
Jul 14, 2009, 3:56:02 PM7/14/09
to pytho...@python.org

!= does do what I want, except that it doesn't indicate to someone reading
the code that the operands are being treated as logicals. (Readability is
supposed to be one of the major selling points of Python). But, this is
probably good enough.

Here's a related issue: I would like to see an option for type checking on
operands of logical operators, so that attempting to apply a logical
operator to non-Boolean entities generates a warning message. With operand
type checking, 'xor' and != would be different.

> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

--
View this message in context: http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24486661.html

Chris Rebert

unread,
Jul 14, 2009, 4:22:20 PM7/14/09
to Dr. Phillip M. Feldman, pytho...@python.org
On Tue, Jul 14, 2009 at 12:56 PM, Dr. Phillip M.
Feldman<pfel...@verizon.net> wrote:
<snip>

> Here's a related issue: I would like to see an option for type checking on
> operands of logical operators, so that attempting to apply a logical
> operator to non-Boolean entities generates a warning message. With operand
> type checking, 'xor' and != would be different.

That's probably not gonna happen. Python is dynamically and duck
typed, and has a sweet coercion system (__bool__ or __nonzero__
depending on your version) to coerce non-booleans to booleans in a
sensible and useful way. So, it's not gonna change any time soon.

Some illustrative examples:
>>> #empty containers considered false
>>> bool([] or {} or set() or "")
>>> False
>>> #zero and null considered false
>>> bool(0 or None)
>>> False
>>> #anything else is, by default, true
>>> bool(object())
>>> True

And like I said, a class can override a special method to provide
whatever boolean semantics are desired. It's surprisingly handy.

Robert Kern

unread,
Jul 14, 2009, 4:59:32 PM7/14/09
to pytho...@python.org
On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:
> != does do what I want, except that it doesn't indicate to someone reading
> the code that the operands are being treated as logicals. (Readability is
> supposed to be one of the major selling points of Python). But, this is
> probably good enough.

In the words of those greater than myself, "Not every one-liner needs to be in
the standard library."

def xor(a, b):
return bool(a) != bool(b)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Ethan Furman

unread,
Jul 14, 2009, 5:38:12 PM7/14/09
to pytho...@python.org
Robert Kern wrote:
> On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:
>
>> != does do what I want, except that it doesn't indicate to someone
>> reading
>> the code that the operands are being treated as logicals.
>> (Readability is
>> supposed to be one of the major selling points of Python). But, this is
>> probably good enough.
>
>
> In the words of those greater than myself, "Not every one-liner needs to
> be in the standard library."
>
> def xor(a, b):
> return bool(a) != bool(b)
>

Let's see...

and returns the last object that is "true"
or returns the first object that is "true"

so should xor return the only object that is "true", else False/None?

def xor(a, b)
if a and b:
return None
elif a:
return a
elif b:
return b
else:
return None

~Ethan~

MRAB

unread,
Jul 14, 2009, 5:58:27 PM7/14/09
to pytho...@python.org
How about:

def xor(a, b):
return not b and a or not a and b

Ethan Furman

unread,
Jul 14, 2009, 6:11:40 PM7/14/09
to pytho...@python.org

In [12]: not 1 and 0 or 1 and not 0
Out[12]: True

In [13]: not 0 and 0 or 0 and not 0
Out[13]: 0

In [14]: not 1 and 1 or 1 and not 1
Out[14]: False

In [15]: not [] and [] or [] and not []
Out[15]: []

Doesn't produce consistent objects, sometimes bool, sometimes something
else. 'Course, it all depends on what you need.

~Ethan~

Christian Heimes

unread,
Jul 14, 2009, 7:08:24 PM7/14/09
to pytho...@python.org
Chris Rebert wrote:
> Using the xor bitwise operator is also an option:
> bool(x) ^ bool(y)

I prefer something like:

bool(a) + bool(b) == 1

It works even for multiple tests (super xor):

if bool(a) + bool(b) + bool(c) + bool(d) != 1:
raise ValueError("Exactly one of a, b, c and d must be true")

Christian

Scott David Daniels

unread,
Jul 14, 2009, 7:36:35 PM7/14/09
to
Ethan Furman wrote:
> and returns the last object that is "true"
A little suspect this.
_and_ returns the first object that is not "true," or the last object.

> or returns the first object that is "true"
Similarly:
_or_ returns the first object that is "true," or the last object.

> so should xor return the only object that is "true", else False/None?

Xor has the problem that in two cases it can return neither of its args.
Not has behavior similar in those cases, and we see it returns False or
True. The Pythonic solution is therefore to use False.

> def xor(a, b)
> if a and b:
> return None
> elif a:
> return a
> elif b:
> return b
> else:
> return None

def xor(a, b):
if bool(a) == bool(b):
return False
else:
return a or b

Side-effect counting in applications of bool(x) is ignored here.
If minimizing side-effects is needed:

def xor(a, b):
if a:
if not b:


return a
elif b:
return b

return False

--Scott David Daniels
Scott....@Acm.Org

Ethan Furman

unread,
Jul 14, 2009, 7:48:26 PM7/14/09
to pytho...@python.org

super_xor! I like it!

In [23]: def super_xor(args, failure=False):
....: found_one = False
....: for item in args:
....: if item:
....: if found_one:
....: return failure
....: else:
....: found_one = item
....: return found_one or failure

In [25]: super_xor((0, 1, 0, []))
Out[25]: 1

In [26]: super_xor((0, 1, 0, [],('this',)))
Out[26]: False

In [27]: super_xor((0, {}, 0, [],()))
Out[27]: False

In [16]: def super_or(args, failure=False):
....: for item in args:
....: if item:
....: return item
....: else:
....: return failure
....:

In [17]: super_or((None, [], 0, 3, {}))
Out[17]: 3

In [18]: super_or((None, [], 0, (), {}))
Out[18]: False

In [19]: def super_and(args, failure=False):
....: for item in args:
....: if not item:
....: return failure
....: else:
....: return item
....:

In [20]: super_and((1, 2, 3))
Out[20]: 3

In [21]: super_and((1, 2, 3, 4))
Out[21]: 4

In [22]: super_and((1, 0, 3, 4))
Out[22]: False

A whole family of supers. :)

~Ethan~

Dr. Phillip M. Feldman

unread,
Jul 15, 2009, 12:07:14 AM7/15/09
to pytho...@python.org

I appreciate the effort that people have made, but I'm not impressed with any
of the answers. For one thing, xor should be able to accept an arbitrary
number of input arguments (not just two), and should return True if and only
if the number of input arguments that evaluate to True is odd (see
www.mathworld.com article on xor). Here's my code:

def xor(*args):
"""xor accepts an arbitrary number of input arguments, returning True
if and only if bool() evaluates to True for an odd number of the input
arguments."""

result= False

for arg in args:
if bool(arg): result= not result

return result

MRAB-2 wrote:
>
> Ethan Furman wrote:
>> Robert Kern wrote:
>>> On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:
>>>
>>>> != does do what I want, except that it doesn't indicate to someone
>>>> reading
>>>> the code that the operands are being treated as logicals.
>>>> (Readability is
>>>> supposed to be one of the major selling points of Python). But, this
>>>> is
>>>> probably good enough.
>>>
>>>
>>> In the words of those greater than myself, "Not every one-liner needs
>>> to be in the standard library."
>>>
>>> def xor(a, b):
>>> return bool(a) != bool(b)
>>>
>>
>> Let's see...
>>

>> and returns the last object that is "true"

>> or returns the first object that is "true"
>>

>> so should xor return the only object that is "true", else False/None?
>>

>> def xor(a, b)
>> if a and b:
>> return None
>> elif a:
>> return a
>> elif b:
>> return b
>> else:
>> return None
>>

> How about:
>
> def xor(a, b):
> return not b and a or not a and b

> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

--
View this message in context: http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24491580.html

Miles Kaufmann

unread,
Jul 15, 2009, 1:08:42 AM7/15/09
to pytho...@python.org
On Jul 15, 2009, at 12:07 AM, Dr. Phillip M. Feldman wrote:

> I appreciate the effort that people have made, but I'm not impressed
> with any
> of the answers. For one thing, xor should be able to accept an
> arbitrary
> number of input arguments (not just two)

You originally proposed this in the context of the existing short-
circuit boolean operators. Those operators (being infix) take only
two operands.

> and should return True if and only
> if the number of input arguments that evaluate to True is odd

The existing and/or operators always return the value of one of the
operands--not necessarily True or False--which is another important
property, but one that can't be translated fully to xor. Given the
lack of context in your original post, hopefully you'll forgive me
being unimpressed by your not being impressed. :)

> Here's my code:
>
> def xor(*args):
> """xor accepts an arbitrary number of input arguments, returning
> True
> if and only if bool() evaluates to True for an odd number of the
> input
> arguments."""
>
> result= False
>
> for arg in args:
> if bool(arg): result= not result
>
> return result

If all you want is a True or False result, I'd write it like this:

import operator
def xor(*args):
return reduce(operator.xor, map(bool, args)) # or imap

In order to make it act more like the other logical operators, I'd use
MRAB's 2-argument xor as the reducer--though I can't really see the
utility.

def xor2(a, b):
return (not b and a) or (not a and b)

def xor(*args):
return reduce(xor2, args)

You may also find this question interesting:

http://stackoverflow.com/questions/432842/

-Miles

Tim Roberts

unread,
Jul 15, 2009, 2:43:10 AM7/15/09
to
"Dr. Phillip M. Feldman" <pfel...@verizon.net> wrote:
>
>Here's a related issue: I would like to see an option for type checking on
>operands of logical operators, so that attempting to apply a logical
>operator to non-Boolean entities generates a warning message. With operand
>type checking, 'xor' and != would be different.

How would you define "Boolean entities"? Do you mean the True and False
values? Such a change would break virtually every Python program ever
written.

In any case, this idea is dead in the water. It would break a whole bunch
of existing code from before the conditional operator:

xxx = testme and truevalue or falsevalue
--
Tim Roberts, ti...@probo.com
Providenza & Boekelheide, Inc.

Mark Dickinson

unread,
Jul 15, 2009, 3:44:48 AM7/15/09
to
On Jul 15, 5:07 am, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>
wrote:

> I appreciate the effort that people have made, but I'm not impressed with any
> of the answers.  For one thing, xor should be able to accept an arbitrary
> number of input arguments (not just two), and should return True if and only
> if the number of input arguments that evaluate to True is odd.

Well, that's not exactly what you originally asked for. But it's
still a one-liner:

def xor(*args): return bool(sum(map(bool, args)) % 2)

or perhaps

def xor(*args): return bool(len(filter(None, args)) & 1)

> Here's my code:
>
> def xor(*args):
>    """xor accepts an arbitrary number of input arguments, returning True
>    if and only if bool() evaluates to True for an odd number of the input
>    arguments."""
>
>    result= False
>
>    for arg in args:
>       if bool(arg): result= not result

It's more idiomatic to say "if arg: ..." rather than "if bool
(arg): ...".

>
>    return result

Mark

Ethan Furman

unread,
Jul 14, 2009, 7:53:37 PM7/14/09
to pytho...@python.org
Scott David Daniels wrote:
> Ethan Furman wrote:
>
>> and returns the last object that is "true"
>
> A little suspect this.
> _and_ returns the first object that is not "true," or the last object.
>
>> or returns the first object that is "true"
>
> Similarly:
> _or_ returns the first object that is "true," or the last object.
>

Thanks for the correction.

~Ethan~

>
> --Scott David Daniels
> Scott....@Acm.Org

Asun Friere

unread,
Jul 15, 2009, 4:55:33 AM7/15/09
to
On Jul 15, 5:44 pm, Mark Dickinson <dicki...@gmail.com> wrote:
> On Jul 15, 5:07 am, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>
> wrote:

[snip]

> >    for arg in args:
> >       if bool(arg): result= not result
>
> It's more idiomatic to say "if arg: ..." rather than "if bool
> (arg): ...".
>

Ah yes, but not once conditional tests, (just like logical operators),
type-check to ensure they have been supplied with Boolean entities. ;)

Jonathan Gardner

unread,
Jul 15, 2009, 5:02:04 AM7/15/09
to
On Jul 14, 4:48 pm, Ethan Furman <et...@stoneleaf.us> wrote:
>
> A whole family of supers.  :)
>

You should pick up Lisp. The whole concept of a binary operator
doesn't exist over there. All the things binary operators can do, Lisp
does with 0, 1, 2, or more arguments.

[1]> (+)
0
[2]> (+ 1)
1
[3]> (+ 1 2)
3
[4]> (+ 1 2 3)
6

Once you get used to that, binary operators don't seem so useful
anymore.

The equivalent in Python is dropping the operators and replacing them
with built-in functions that take 0, 1, 2, or more arguments.

Steven D'Aprano

unread,
Jul 15, 2009, 5:11:44 AM7/15/09
to
On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:

> Current Boolean operators are 'and', 'or', and 'not'. It would be nice
> to have an 'xor' operator as well.

I've often wished there was too, for the sake of completeness and
aesthetics, I'd love to be able to write:

a xor b

instead of defining a function xor(a, b).

Unfortunately, outside of boolean algebra and simulating electrical
circuits, I can't think of any use-cases for an xor operator. Do you have
any?

--
Steven

pdpi

unread,
Jul 15, 2009, 5:17:09 AM7/15/09
to

"if bool(a) + bool(b) + bool(c) + bool(d) != 1:" is not equivalent to
xor. 1 xor 1 xor 1 = 1 xor (1 xor 1) = 1 xor 0 = 1 (or = (1 xor 1) xor
1 = 0 xor 1 = 1 if you assicate to the left)

Tim Wintle

unread,
Jul 15, 2009, 5:28:34 AM7/15/09
to pytho...@python.org

On Wed, 2009-07-15 at 02:02 -0700, Jonathan Gardner wrote:
> On Jul 14, 4:48 pm, Ethan Furman <et...@stoneleaf.us> wrote:
> >
> > A whole family of supers. :)
> >
> All the things binary operators can do, Lisp
> does with 0, 1, 2, or more arguments.

+1

n-ary operators are great, but binary operators are just syntactic sugar
for functions (which are obviously a generalisation of an n-ary operator
in python).

The fact that lisp-like languages don't expose this sugar is good for
making you think about what you're actually doing, but just like
mathematicians use binary (and unary) operators in equations rather than
working in the lambda calculus, having that sugar is useful to python.

>
> [1]> (+)
> 0
> [2]> (+ 1)
> 1
> [3]> (+ 1 2)
> 3
> [4]> (+ 1 2 3)
> 6

c.f. :

>>> sum([])
0
>>> sum([1])
1
>>> sum([1,2])
3
>>> sum([1,2,3])

Tim Golden

unread,
Jul 15, 2009, 5:32:55 AM7/15/09
to pytho...@python.org

I was pondering on this yesterday, and the only case I've
come across in my code -- and it's reasonably common --
is checking that one and only one of two params has been
passed. I have code which wants, say, an id or a name
but doesn't want both. It's hardly difficult to write the
check even now, but an built-in xor would make it fractionally
cleaner.

TJG

Christian Heimes

unread,
Jul 15, 2009, 7:37:22 AM7/15/09
to pytho...@python.org

I'm well aware of the fact that I've described something differently.
'xor' can be explained as 'check if exactly one element of two elements
is true'. My algorithms describes a super xor, aka 'check if exactly one
element of n elements is true'.

Christian

pdpi

unread,
Jul 15, 2009, 9:12:03 AM7/15/09
to

Well, I just wouldn't call it a "super xor" then, when "unicity test"
works much better -- especially as an alternative to an actual xor
without any specification to the actual intended functionality except
the exception text.

Hendrik van Rooyen

unread,
Jul 15, 2009, 9:37:30 AM7/15/09
to pytho...@python.org

"Steven D'Aprano" <ste...@REMOVE.THIS.cy..e.com.au> wrote:

>Unfortunately, outside of boolean algebra and simulating electrical
>circuits, I can't think of any use-cases for an xor operator. Do you have
>any?

A bitwise xor is a poor man's comparator - if the result is binary zero,
the operands were equal, no matter what they represented.

Not much use in python, though.

- Hendrik


MRAB

unread,
Jul 15, 2009, 10:21:27 AM7/15/09
to pytho...@python.org
The problem is that 'and' and 'or' are not limited to Boolean values:

'and' returns the first false value or the last true value.

'or' returns the first true value or the last false value.

What values should 'xor' return? IMHO, if only one of the values is true
then it should return that value, otherwise it should return False.

1 xor 0 => 1

0 xor 2 => 2
1 xor 2 => False
0 xor 0 => False

This is because it's a Boolean operator, so it should fall back to
Boolean values when necessary, like 'not':

not 0 => True
not 1 => False

Also:

x and y and z => (x and y) and z
x or y or z => (x or y) or z

therefore:

x xor y xor z => (x xor y) xor z

Bill Davy

unread,
Jul 15, 2009, 10:37:54 AM7/15/09
to
"MRAB" <pyt...@mrabarnett.plus.com> wrote in message
news:mailman.3158.1247667...@python.org...


Gosh, let's all discuss commutation and distribution.

And surely in quantum merchanics there is something about non-commuting
operatiomns letting in Planck's constant.


Jean-Michel Pichavant

unread,
Jul 15, 2009, 11:15:47 AM7/15/09
to Christian Heimes, pytho...@python.org
Christian Heimes wrote:
> Chris Rebert wrote:
>
>> Using the xor bitwise operator is also an option:
>> bool(x) ^ bool(y)
>>
>
> I prefer something like:
>
> bool(a) + bool(b) == 1
>
> It works even for multiple tests (super xor):
>
> if bool(a) + bool(b) + bool(c) + bool(d) != 1:
> raise ValueError("Exactly one of a, b, c and d must be true")
>
> Christian
>
>
While everyone's trying to tell the OP how to workaround the missing xor
operator, nobody answered the question "why is there no xor operator ?".

If the question was "Why is there no 'or' operator ?", would "because A
or B <=> not(not A and not B)" be a proper answer ?

JM

Robert Kern

unread,
Jul 15, 2009, 11:38:55 AM7/15/09
to pytho...@python.org

That's not the only answer the OP has been given. The most compelling answer is
that an "xor" keyword cannot be implemented with similar semantics to "and" and
"or", in particular short-circuiting and returning one of the actual inputs
instead of a coerced bool.

Hrvoje Niksic

unread,
Jul 15, 2009, 12:14:10 PM7/15/09
to
Jean-Michel Pichavant <jeanm...@sequans.com> writes:

> While everyone's trying to tell the OP how to workaround the missing

> xor operator, nobody answered the question "why is there no [boolean]
> xor operator ?".

Probably because there isn't one in C. The bitwise XOR operator, on the
other hand, exists in both C and Python.

> If the question was "Why is there no 'or' operator ?", would "because
> A or B <=> not(not A and not B)" be a proper answer ?

Note that in Python A or B is in fact not equivalent to not(not A and
not B).

Paul Rubin

unread,
Jul 15, 2009, 1:25:25 PM7/15/09
to
Hrvoje Niksic <hni...@xemacs.org> writes:
> > While everyone's trying to tell the OP how to workaround the missing
> > xor operator, nobody answered the question "why is there no [boolean]
> > xor operator ?".
>
> Probably because there isn't one in C. The bitwise XOR operator, on the
> other hand, exists in both C and Python.

A non-bitwise XOR really sounds almost useless.

Wayne Brehaut

unread,
Jul 15, 2009, 1:36:21 PM7/15/09
to

But that's not a "super xor" (commonly known as XOR). Rather than
describing xor as:

check if exactly one element of two elements is true

describe it as:

check if an odd number of two elements is true

then you'll get the correct definition of "super xor":

check if an odd number of n elements is true

I.e., XOR determines parity, and:

XOR <some binary vector v> =
0 if v has an even number of 1s and
1 if v has an odd number of 1s

wayne

>Christian

Jean-Michel Pichavant

unread,
Jul 15, 2009, 1:43:20 PM7/15/09
to Hrvoje Niksic, pytho...@python.org
Hrvoje Niksic wrote:
[snip]

> Note that in Python A or B is in fact not equivalent to not(not A and
> not B).
>
>>> l = [(True, True), (True, False), (False, True), (False, False)]
>>> for p in l:
... p[0] or p[1]
...
True
True
True
False
>>> for p in l:
... not(not p[0] and not p[1])
...
True
True
True
False
>>>

Did I make twice the same obvious error ?

JM

Emile van Sebille

unread,
Jul 15, 2009, 1:55:22 PM7/15/09
to pytho...@python.org
On 7/15/2009 10:43 AM Jean-Michel Pichavant said...
> Hrvoje Niksic wrote:
> [snip]

>> Note that in Python A or B is in fact not equivalent to not(not A and
>> not B).
>>
> >>> l = [(True, True), (True, False), (False, True), (False, False)]
> >>> for p in l:
> ... p[0] or p[1]
> ...
> True
> True
> True
> False
> >>> for p in l:
> ... not(not p[0] and not p[1])
> ...
> True
> True
> True
> False
> >>>
> Did I make twice the same obvious error ?

No -- but in the not(not... example it doesn't short-circuit.

Emile

Miles Kaufmann

unread,
Jul 15, 2009, 1:57:20 PM7/15/09
to pytho...@python.org

On Jul 15, 2009, at 1:43 PM, Jean-Michel Pichavant wrote:

> Hrvoje Niksic wrote:
> [snip]


>> Note that in Python A or B is in fact not equivalent to not(not A and
>> not B).
>>

> >>> l = [(True, True), (True, False), (False, True), (False, False)]
> >>> for p in l:
> ... p[0] or p[1]

> [snip]


> Did I make twice the same obvious error ?


Try again with:

l = [('foo','bar'), ('foo', ''), ('', 'bar'), ('', '')]

-Miles

Miles Kaufmann

unread,
Jul 15, 2009, 2:10:50 PM7/15/09
to pytho...@python.org
On Jul 15, 2009, at 1:55 PM, Emile van Sebille wrote:
> On 7/15/2009 10:43 AM Jean-Michel Pichavant said...
>> Hrvoje Niksic wrote:
>> [snip]
>>> Note that in Python A or B is in fact not equivalent to not(not A
>>> and
>>> not B).
>>>
>> Did I make twice the same obvious error ?
>
> No -- but in the not(not... example it doesn't short-circuit.

No; like 'A or B', 'not (not A and not B)' does in fact short-circuit
if A is True. (The 'and' condition does not have to evaluate the
right operand when 'not A' is False.)

-Miles

Terry Reedy

unread,
Jul 15, 2009, 2:14:55 PM7/15/09
to pytho...@python.org
Tim Golden wrote:

> I was pondering on this yesterday, and the only case I've
> come across in my code -- and it's reasonably common --
> is checking that one and only one of two params has been
> passed. I have code which wants, say, an id or a name
> but doesn't want both. It's hardly difficult to write the
> check even now, but an built-in xor would make it fractionally
> cleaner.

I think I would just have one parameter id_name or identifier so no
check is needed. This is a common idiom in Python where names are not
typed. Example: param 'source' is a string (with a file name to be
opened) or an already opened file. If you want two local vars inside the
function, that should be kept private to the function.

tjr

Dr. Phillip M. Feldman

unread,
Jul 15, 2009, 2:19:18 PM7/15/09
to pytho...@python.org

I did initially ask for an infix xor operator, but eventually gave up on
this. I like the first of your two one-line solutions below; this is clean
and easy to understand. Thanks! I'd still like to be able to write an
expression like '(a and b) xor (c and d) xor (e and f)', but it looks as
though that can't be done.

<snip>

Well, that's not exactly what you originally asked for. But it's
still a one-liner:

def xor(*args): return bool(sum(map(bool, args)) % 2)

or perhaps

def xor(*args): return bool(len(filter(None, args)) & 1)

--
View this message in context: http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24503248.html
Sent from the Python - python-list mailing list archive at Nabble.com.

Wayne Brehaut

unread,
Jul 15, 2009, 2:29:54 PM7/15/09
to
On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson
<dick...@gmail.com> wrote:

>On Jul 14, 7:25�pm, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>


>wrote:
>> Current Boolean operators are 'and', 'or', and 'not'. �It would be nice to
>> have an 'xor' operator as well.
>

>Hmm. I don't think 'nice' is sufficient. You'd need to make the case
>that it's sufficiently useful to justify adding a new keyword 'xor' to
>the language; I suspect that would be an uphill struggle. :)
>
>I'll just note that:
>
>(1) It's easy to emulate xor: 'x xor y' <-> bool(x) != bool(y)
>
>(2) 'and' and 'or' are special in that they have useful short-
>circuiting behaviour; xor doesn't have this property (that is, you
>always need to evaluate *both* operands to determine the result).
>
>I'd also guess that 'xor' would be much less used than 'and' or 'or',
>but maybe that's just a reflection of the sort of code that I tend to
>write.

You're right about that!. It's used everywhere in:

- coding and encryption theory (and practice) (e.g.,
http://www.mathcs.emory.edu/~whalen/Hash/Hash_Articles/IEEE/XOR-based%20hash%20functions.pdf)
- emulation and simulation of hardware (since all but the most trivial
logic circuits are likely to include XOR-gates)
- hence, for design of new architectures or simulators or virtual
machines and simplification of existing ones--(e.g.,
http://www.date-conference.com/archive/conference/proceedings/PAPERS/1999/DATE99/PDFFILES/05A_6.PDF)
and
http://bochs.sourceforge.net/Virtualization_Without_Hardware_Final.pdf
which includes:

"The answer relies on the observation that subtracting an integer
value from 0xFFFFFFFF gives the same result as XOR-ing that same value
to 0xFFFFFFFF."

And, perhaps the most useful use of all, for Bouton's solution of the
game of Nim--both for the proof that his strategy "solves" the game
and for an easy implementation of a Nim-playing program--and the only
operator needed is XOR (e.g., http://www.wordiq.com/definition/Nim).

wayne

Robert Kern

unread,
Jul 15, 2009, 2:47:28 PM7/15/09
to pytho...@python.org

All of those can use the bitwise XOR operator, not the boolean XOR. Python
already has the ^ operator for those purposes.

Mark Dickinson

unread,
Jul 15, 2009, 2:51:44 PM7/15/09
to
On Jul 15, 7:29 pm, Wayne Brehaut <wbreh...@mcsnet.ca> wrote:

> On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson <dicki...@gmail.com> wrote:
> >I'd also guess that 'xor' would be much less used than 'and' or 'or',
> >but maybe that's just a reflection of the sort of code that I tend to
> >write.
>
> You're right about that!. It's used everywhere in:
> [snip examples and references]

Those examples are (almost) all about the *bitwise* xor operator,
which exists in Python ('^') and, as you point out, has no shortage of
good uses. The discussion was about a *logical* xor, to parallel the
existing 'and' and 'or' operators.

--
Mark

Anthony Tolle

unread,
Jul 15, 2009, 2:53:23 PM7/15/09
to
On Jul 14, 2:25 pm, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>

wrote:
> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
> have an 'xor' operator as well.

My $0.02 on this discussion: There would be nothing gained by having
non-bitwise XOR operator. You can't short-circuit XOR, because you
must evaluate all operands to produce a result. Consequently,
returning the "true" item also doesn't make much sense. XOR is closer
to the the logical NOT operator than it is to AND or OR.

Here's my own take on a function that can handle any number of
arguments (it should probably raise an exception for 0 or 1 arguments,
but I'm lazy):

def xor(*operands):
if operands:
operands = list(operands)
a = bool(operands.pop(0))
while operands:
b = bool(operands.pop(0))
if a:
if b:
a = False
elif b:
a = True
return a
return False

Jean-Michel Pichavant

unread,
Jul 15, 2009, 3:05:16 PM7/15/09
to Miles Kaufmann, pytho...@python.org
Miles Kaufmann wrote:
>
> On Jul 15, 2009, at 1:43 PM, Jean-Michel Pichavant wrote:
>
>> Hrvoje Niksic wrote:
>> [snip]
>>> Note that in Python A or B is in fact not equivalent to not(not A and
>>> not B).
>>>
>> >>> l = [(True, True), (True, False), (False, True), (False, False)]
>> >>> for p in l:
>> ... p[0] or p[1]
>> [snip]
>> Did I make twice the same obvious error ?
>
>
> Try again with:
>
> l = [('foo','bar'), ('foo', ''), ('', 'bar'), ('', '')]
>
> -Miles
>
Didn't know that.
So if I resume:
- not 'foo' => False
- 'foo' or 'foo' => 'foo'

I may be missing something, but honestly, Guido must have smoked some
heavy stuff to write such logic, has he ?

Let's play again
False or 'foo' => 'foo'
False and 'foo' => False

So funny. I would have expected boolean operators to return a boolean
value. I should have read the f*** manual (this is an anticipated RTFM
counter-attack). Anyway Miles, thanks for the update.

JM

Wayne Brehaut

unread,
Jul 15, 2009, 3:55:08 PM7/15/09
to

I thought you were saying your program domains didn't include a lot of
requirements for xor in general, rather than just no uses for Boolean
xor--and I'm used to thinking of xor on binary vectors as "Boolean"
anyway so would still have been confused.

The most common non-binary-bit-wise xor is the general "symmetric
difference" of sets, most likely to be useful in list or dictionary
processing or database-like contexts. Please see my suggested use-case
for Steven below.

wayne

Hrvoje Niksic

unread,
Jul 15, 2009, 4:00:52 PM7/15/09
to
Jean-Michel Pichavant <jeanm...@sequans.com> writes:

> Hrvoje Niksic wrote:
> [snip]
>> Note that in Python A or B is in fact not equivalent to not(not A and
>> not B).
>>
>>>> l = [(True, True), (True, False), (False, True), (False, False)]
>>>> for p in l:
> ... p[0] or p[1]

[...]

Try with a different data set, for example:

>>> 10 or 20
10
>>> not(not 10 and not 20)
True

Wayne Brehaut

unread,
Jul 15, 2009, 6:54:00 PM7/15/09
to
On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson
<dick...@gmail.com> wrote:

>On Jul 14, 7:25�pm, "Dr. Phillip M. Feldman" <pfeld...@verizon.net>


>wrote:
>> Current Boolean operators are 'and', 'or', and 'not'. �It would be nice to
>> have an 'xor' operator as well.
>

>Hmm. I don't think 'nice' is sufficient. You'd need to make the case
>that it's sufficiently useful to justify adding a new keyword 'xor' to
>the language; I suspect that would be an uphill struggle. :)

=== 8< ===
And for the objects for which it *is* sufficiently useful (sets) the
xor operator ^ is available:

>>> cheese = set(['cheddar', 'limburger', 'stilton'])
>>> stinky = set(['skunk', 'limburger', 'stilton', 'polecat', 'doggy-doo', 'civet'])
>>> nasty = set(['doggy-doo', 'polecat', 'limburger', 'Perl'])
>>> cheese & stinky # stinky cheese
set(['limburger', 'stilton'])
>>> cheese ^ stinky # either cheese or stinky but not both
set(['doggy-doo', 'civet', 'polecat', 'skunk', 'cheddar'])
>>> cheese ^ stinky ^ nasty # in an odd number of these sets (1 or 3)
set(['civet', 'cheddar', 'Perl', 'limburger', 'skunk'])

wayne

Wayne Brehaut

unread,
Jul 15, 2009, 6:57:59 PM7/15/09
to
On 15 Jul 2009 09:11:44 GMT, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:

>On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:
>
>> Current Boolean operators are 'and', 'or', and 'not'. It would be nice
>> to have an 'xor' operator as well.
>

>I've often wished there was too, for the sake of completeness and
>aesthetics, I'd love to be able to write:
>
>a xor b
>
>instead of defining a function xor(a, b).
>
>Unfortunately, outside of boolean algebra and simulating electrical
>circuits, I can't think of any use-cases for an xor operator. Do you have
>any?

Since xor in set theory is the symmetric difference, perhaps we'd
like to know all items in exactly one of two word lists or
dictionaries, or anything else we could easily set-ize:

>>> cheese = set(['cheddar', 'limburger', 'stilton'])
>>> stinky = set(['skunk', 'limburger', 'stilton', 'polecat', 'doggy-doo', 'civet'])
>>> nasty = set(['doggy-doo', 'polecat', 'limburger', 'Perl'])
>>> cheese & stinky # stinky cheese
set(['limburger', 'stilton'])
>>> cheese ^ stinky # either cheese or stinky but not both
set(['doggy-doo', 'civet', 'polecat', 'skunk', 'cheddar'])
>>> cheese ^ stinky ^ nasty # in an odd number of these sets (1 or 3)
set(['civet', 'cheddar', 'Perl', 'limburger', 'skunk'])

Who hasn't needed that occasionally?

wayne

Chris Rebert

unread,
Jul 15, 2009, 7:02:13 PM7/15/09
to Wayne Brehaut, pytho...@python.org

This discussion is about adding a *logical* operator for use in
boolean expressions. We obviously already have ^ for non-boolean use.

Cheers,
Chris
--
http://blog.rebertia.com

Nobody

unread,
Jul 15, 2009, 7:01:37 PM7/15/09
to
On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote:

> So if I resume:
> - not 'foo' => False
> - 'foo' or 'foo' => 'foo'
>
> I may be missing something, but honestly, Guido must have smoked some
> heavy stuff to write such logic, has he ?

Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. "or"
returns the first element which is considered true while "and" returns the
last element provided that all preceding elements are considered true.

> Let's play again
> False or 'foo' => 'foo'
> False and 'foo' => False
>
> So funny. I would have expected boolean operators to return a boolean
> value.

In Python, almost everything is a boolean value.

Compare with Lisp, where everything is a boolean value: nil (the empty
list) is false and everything else (including integer zero) is true.

Paul Rubin

unread,
Jul 15, 2009, 8:32:34 PM7/15/09
to
Anthony Tolle <anthon...@gmail.com> writes:
> def xor(*operands):
> if operands:
> operands = list(operands)
> a = bool(operands.pop(0))
> while operands:
> b = bool(operands.pop(0))
> if a:
> if b:
> a = False
> elif b:
> a = True
> return a
> return False

Among other things, that uses quadratic time! Why do you want to keep
popping items from that list instead of iterating through it anyway?

Anyway, I think you wrote something close to this:

def xor(*operands):
r = False
for x in operands:
r = (r != bool(x))
return r

or in map-reduce style:

from operator import ne
def xor(*operands):
return reduce(ne, map(bool, operands), False)

Steven D'Aprano

unread,
Jul 16, 2009, 1:37:02 AM7/16/09
to
On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote:

> Didn't know that.
> So if I resume:
> - not 'foo' => False
> - 'foo' or 'foo' => 'foo'
>
> I may be missing something, but honestly, Guido must have smoked some
> heavy stuff to write such logic, has he ?

No, it's perfectly reasonable, and not at all the product of mind-
altering drugs. Other languages do the same thing.


for x in alist or blist or clist:
print x

will select the first non-empty list and iterate over that.

Every object in Python has a truth value. By convention, we say that
objects are Something or Nothing.

0 None [] '' are examples of Nothing, or false values.

1 2.5 [x, y, z] 'foo' are examples of Something, or true values.

Note the distinction between lower-case "false" and "true" (adjectives),
and title-case False and True (nouns).


`if x: ... else:` branches according to whether x is Something or
Nothing, not whether it is True or False.

The operators `and` and `or` also return Something or Nothing, short-
circuiting as appropriate.

--
Steven

Hendrik van Rooyen

unread,
Jul 16, 2009, 3:43:53 AM7/16/09
to pytho...@python.org
"Hrvoje Niksic" <hniksic@x..s.org> wrote:


> Note that in Python A or B is in fact not equivalent to not(not A and
> not B).

De Morgan would turn in his grave.

- Hendrik


Steven D'Aprano

unread,
Jul 16, 2009, 4:19:21 AM7/16/09
to

No he wouldn't. Python isn't Boolean algebra, and there is no requirement
to limit Python's operators to the semantics of Boolean algebra.

--
Steven

Lino Mastrodomenico

unread,
Jul 16, 2009, 5:02:55 AM7/16/09
to Hendrik van Rooyen, pytho...@python.org
2009/7/16 Hendrik van Rooyen <ma...@microcorp.co.za>:

> "Hrvoje Niksic" <hniksic@x..s.org> wrote:
>
>
>> Note that in Python A or B is in fact not equivalent to not(not A and
>> not B).
>
> De Morgan would turn in his grave.

If this can make him happier, in Python (not (not a and not b)) *is*
equivalent to bool(a or b). (Modulo crazy things like redefining
"bool" or having a __bool__ with side effects.)

In the first expression you implicitly request a bool because you use
"not", in the second one you do this with an explicit "bool".

--
Lino Mastrodomenico

Jean-Michel Pichavant

unread,
Jul 16, 2009, 5:06:54 AM7/16/09
to Nobody, pytho...@python.org
Nobody wrote:
> On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote:
>
>
>> So if I resume:
>> - not 'foo' => False
>> - 'foo' or 'foo' => 'foo'
>>
>> I may be missing something, but honestly, Guido must have smoked some
>> heavy stuff to write such logic, has he ?
>>
>
> Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. "or"
> returns the first element which is considered true while "and" returns the
> last element provided that all preceding elements are considered true.
>
> [snip]
>

Ok then, why "or" does not return True, if the first element is
considered True ? Why returning the element itself. Any reason for that
? Because it's confusing, maybe people used to that logic find it
obvious, but I really don't.

JM

Anthony Tolle

unread,
Jul 16, 2009, 9:23:57 AM7/16/09
to
On Jul 15, 8:32 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Among other things, that uses quadratic time!  Why do you want to keep
> popping items from that list instead of iterating through it anyway?
>
> Anyway, I think you wrote something close to this:
> ...

Very true! I didn't think about the problems with pop(). I was using
it as a shortcut for pulling off the first operand. I forgot that if
you start with an initial operand of "False", the result will be the
same (0 xor X = X)

While I'm not sure how useful it would be, here's a version of the
first function that returns one of the operands (ala AND and OR),
except in the case where there is an even number of True elements,
where it returns False:

def xor(*operands):
r, rprime = False, False
for x in operands:
xprime = bool(x)
if rprime:
if xprime:
r, rprime = False, False
else:
r, rprime = x, xprime
return r

>>> xor(0, 0)
0
>>> xor(0, 1)
1
>>> xor(1, 0)
1
>>> xor(1, 1)
False
>>> xor(0, 1, 2)
False
>>> xor(0, 1, 2, 3)
3
>>> xor(None, [])
[]

Emile van Sebille

unread,
Jul 16, 2009, 9:34:34 AM7/16/09
to pytho...@python.org
On 7/16/2009 2:06 AM Jean-Michel Pichavant said...

> Ok then, why "or" does not return True, if the first element is
> considered True ? Why returning the element itself. Any reason for that
> ? Because it's confusing, maybe people used to that logic find it
> obvious, but I really don't.

For example, I sometimes use it to set defaults:

daysInAdvance = int(inputVar) or 25

Emile

Jean-Michel Pichavant

unread,
Jul 16, 2009, 9:53:45 AM7/16/09
to Emile van Sebille, pytho...@python.org
Sure this looks like an elegant way to set default values and I will use
this form , but I'm not sure this justifies by itself the trickery.
Python has extended the algebra definition of "or" and "and" top any
type, but it is so unintuitive (I'm no LISP programmer). I think than
using the short-circuiting mechanism of bool operators along with the
python tricks is just error prone and may result in bug difficult to
spot, unless you are very aware of all python boolean mechanisms.

JM

Grant Edwards

unread,
Jul 16, 2009, 10:04:34 AM7/16/09
to

I don't get it. That doesn't work right when inputVar == "0".

--
Grant Edwards grante Yow! What I want to find
at out is -- do parrots know
visi.com much about Astro-Turf?

Emile van Sebille

unread,
Jul 16, 2009, 12:23:43 PM7/16/09
to pytho...@python.org
On 7/16/2009 7:04 AM Unknown said...

> On 2009-07-16, Emile van Sebille <em...@fenx.com> wrote:
>> daysInAdvance = int(inputVar) or 25
>
> I don't get it. That doesn't work right when inputVar == "0".
>
Aah, but you didn't get to define right. :) For that particular
example 0 is not a valid response.

Emile

Jean-Michel Pichavant

unread,
Jul 16, 2009, 12:37:45 PM7/16/09
to Python List
Emile van Sebille wrote:
> On 7/16/2009 7:04 AM Unknown said...
>> On 2009-07-16, Emile van Sebille <em...@fenx.com> wrote:
>>> daysInAdvance = int(inputVar) or 25
>>
>> I don't get it. That doesn't work right when inputVar == "0".
>>
> Aah, but you didn't get to define right. :) For that particular
> example 0 is not a valid response.
>
> Emile
>
When I was talking about such error prone form of boolean operations, I
didn't expect to be right so quickly :p
Steven explained the truth notion with the Something/Nothing. "0" is
Something, 0 would be Nothing. I'm not sure it makes sens anyway. I
mean, I could easily argue that the number 0 is something. In the end I
wonder if I shouldn't just acknowledge the python mechanism without
trying to find any intuitive/natural/obvious logic in it, knowing that
sometimes the Truth lies far away from the Evidence.

JM

Luis Alberto Zarrabeitia Gomez

unread,
Jul 16, 2009, 3:57:02 PM7/16/09
to Python List

Quoting Jean-Michel Pichavant <jeanm...@sequans.com>:

> Emile van Sebille wrote:
> > On 7/16/2009 7:04 AM Unknown said...

> >> On 2009-07-16, Emile van Sebille <em...@fenx.com> wrote:
> >>> daysInAdvance = int(inputVar) or 25
> >>
> >> I don't get it. That doesn't work right when inputVar == "0".
> >>

> > Aah, but you didn't get to define right. :) For that particular
> > example 0 is not a valid response.
>

> When I was talking about such error prone form of boolean operations, I
> didn't expect to be right so quickly :p

What do you mean by being "right so quickly", and "error prone" in this context?
I would also ask "Unknown" why he believes that "int(intputVar) or 25" doesn't
work right when inputVar == "0". The only false value that int() may return is
zero, so the "or 25" clause is there only for that case. I can't see then how
you think that is an error.

> I'm not sure it makes sens anyway. I
> mean, I could easily argue that the number 0 is something. In the end I
> wonder if I shouldn't just acknowledge the python mechanism

Then look it another way. The "Empty/Nothing" is just standard practice, there
is nothing in python that forces you to be "false" if you are empty, or true
otherwise. Instead, answer this: why do you need a /boolean/ value? Is there any
case where you need to be certain that the object's type is 'bool'? If you think
the answer is "yes", you may want to get more familiar with the "duck typing"
concept. (That doesn't mean that there are no legitimate cases where duck typing
is inappropriate, but that there are many cases where people, specially if they
come from statically typed languages, may believe that it is inappropriate when
it isn't).

In the python world, one should care more about how an object /behaves/ than
from what clase it came. If something quacks like a duck, then assume that it is
a duck, at least for the quacking part.

Most python objects carry a truth value. Sometimes it feels natural (None is
"false", boolean True and False are "true" and "false", empty containers are
expected to be false, 0 and '' are "false"). Sometimes, it is everything but
natural, but that's a problem with the object's implementation (datetime.time
comes to mind). So, you shouldn't care if you have a bool instance - it should
be enough that it behaves like a bool (though, if you need a bool, you can
always construct one). The "True or False" expression could return Giraffes, as
long as Giraffes behave like the bool "True" in boolean context. If you care
about the class of the result, you can ask for its truth value, and if you don't
care about it, you can just ignore it, and use it as you would use a bool.

And then, if you can return any object as long as it behaves properly, what
would be better to return? A new bool? Why not new Giraffe, if they will have
the same behaviour? Guido chose to return the a value that will say more about
the result of the operation than just a boolean. It acts as a boolean - if you
don't need anything else, treat it as such -, but it will be, whenever is
possible, one of the objects in the sequence, in case you need more info.

> without
> trying to find any intuitive/natural/obvious logic in it, knowing that
> sometimes the Truth lies far away from the Evidence.

Don't do that. Many of python's decisions are very well thought. You may
disagree with them, as I do with some, but they are rarely taken lightly. And
this is one that I find very agreeable and in line with the rest of python's
philosophy.

--
Luis Zarrabeitia
Facultad de Matem�tica y Computaci�n, UH
http://profesores.matcom.uh.cu/~kyrie

--
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba
http://www.universidad2010.cu

Nobody

unread,
Jul 16, 2009, 4:25:50 PM7/16/09
to
On Thu, 16 Jul 2009 11:06:54 +0200, Jean-Michel Pichavant wrote:

>>> So if I resume:
>>> - not 'foo' => False
>>> - 'foo' or 'foo' => 'foo'
>>>
>>> I may be missing something, but honestly, Guido must have smoked some
>>> heavy stuff to write such logic, has he ?
>>
>> Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. "or"
>> returns the first element which is considered true while "and" returns the
>> last element provided that all preceding elements are considered true.
>>
>> [snip]
>>
>
> Ok then, why "or" does not return True, if the first element is
> considered True ?

If the first element is true, returning the first element is returning
true.

> Why returning the element itself. Any reason for that ?

Why not? Where is the benefit in collapsing all true values to True? You
can convert values to True/False with bool(), but the conversion cannot be
reversed.

It only makes a difference if you are interested in the representation
rather than the value. Do you normally test for equality with "is" or "=="?

Nobody

unread,
Jul 16, 2009, 4:29:07 PM7/16/09
to
On Wed, 15 Jul 2009 18:14:10 +0200, Hrvoje Niksic wrote:

>> If the question was "Why is there no 'or' operator ?", would "because
>> A or B <=> not(not A and not B)" be a proper answer ?


>
> Note that in Python A or B is in fact not equivalent to not(not A and
> not B).

Ah, but it *is* "equivalent"; it isn't "identical", but that's not the
point.

Emile van Sebille

unread,
Jul 16, 2009, 5:59:22 PM7/16/09
to pytho...@python.org
On 7/16/2009 1:29 PM Nobody said...

I'm not sure I'd call it equivalent. A or B returns either unaltered,
and not(not A and not B) always returns a boolean. The equivalent would
be not(not( A or B )).

Emile

Nobody

unread,
Jul 16, 2009, 9:16:53 PM7/16/09
to
On Thu, 16 Jul 2009 14:59:22 -0700, Emile van Sebille wrote:

>>>> If the question was "Why is there no 'or' operator ?", would "because
>>>> A or B <=> not(not A and not B)" be a proper answer ?
>>> Note that in Python A or B is in fact not equivalent to not(not A and
>>> not B).
>>
>> Ah, but it *is* "equivalent"; it isn't "identical", but that's not the
>> point.
>
> I'm not sure I'd call it equivalent.

That depends upon what definition of "equivalent" you are using. Apart
from all manner of vague, informal definitions, there is a formal
definition:

A relation "=" is an equivalence relation if the following hold for all
x, y, and z:

x = x
x = y => y = x
x = y and y = z => x = z

An equivalence relation partitions its domain into equivalence classes,
such that an element is "=" (equivalent) to every element in the same
class, and not "=" to every element in every other class.

This is a lesser notion of equality to "identity", which also requires
that x = y => f(x) = f(y) for all f.

Python's notion of boolean values treats x and y as equivalent if
bool(x) == bool(y).

On this basis, the result of "A or B" is *equivalent* to the result of
"not(not A and not B)". If you use either result as a boolean value (e.g.
the test of an "if" or "while" statement, as an operand to "and" or "or",
etc), the effect is the same. The results aren't *identical*, as there
exist ways to distinguish the two.

As for the utility of this behaviour, returning an actual value rather
than True/False allows the operators to be used as "gates". The term
"gate" in digital logic follows from the axioms:

0 and x = 0
1 and x = x

0 or x = x
1 or x = 1

[0 = False, 1 = True]

If you consider the left operand as the "control" and the right operand as
the "data", the control determines whether or not the data can pass
through the gate to the output (i.e. whether the gate is open or closed).

In Python:

and:
False and 7 => False
False and 0 => False
True and 7 => 7
True and 0 => 0

or:
False or 7 => 7
False or 0 => 0
True or 7 => True
True or 0 => True


Jean-Michel Pichavant

unread,
Jul 17, 2009, 7:06:26 AM7/17/09
to Python List
Luis Alberto Zarrabeitia Gomez wrote:
> Quoting Jean-Michel Pichavant <jeanm...@sequans.com>:
>
>
>> Emile van Sebille wrote:
>>
>>> On 7/16/2009 7:04 AM Unknown said...
>>>
>>>> On 2009-07-16, Emile van Sebille <em...@fenx.com> wrote:
>>>>
>>>>> daysInAdvance = int(inputVar) or 25
>>>>>
>>>> I don't get it. That doesn't work right when inputVar == "0".
>>>>
>>>>
>>> Aah, but you didn't get to define right. :) For that particular
>>> example 0 is not a valid response.
>>>
>> When I was talking about such error prone form of boolean operations, I
>> didn't expect to be right so quickly :p
>>
>
> What do you mean by being "right so quickly", and "error prone" in this context?
> I would also ask "Unknown" why he believes that "int(intputVar) or 25" doesn't
> work right when inputVar == "0". The only false value that int() may return is
> zero, so the "or 25" clause is there only for that case. I can't see then how
> you think that is an error.
>

I was saying that using boolean operators with object instead of boolean
values is error prone, cause no language behaves he same way, and all
behaviors are conventions difficult to figure out without diving deeply
into the documentation (or being explained as it happened to me).

I think the initialization trick is an error, because I don't want
foo(0) to set daysInAdvance to 25. I'll want it to set the attribute to
0, cause 0 is a valid integer. 0 is a valid integer content, None
wouldn't be a valid integer content.


JM

Steven D'Aprano

unread,
Jul 17, 2009, 9:42:44 AM7/17/09
to
On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:

> Python has extended the algebra definition of "or" and "and" top any
> type, but it is so unintuitive (I'm no LISP programmer).

I disagree. The Something/Nothing dichotomy is so intuitive to me that I
would hate to go back to a language that only accepted booleans as
arguments to `if`.


> I think than
> using the short-circuiting mechanism of bool operators along with the
> python tricks is just error prone and may result in bug difficult to
> spot, unless you are very aware of all python boolean mechanisms.

In other words, if you don't know how Python behaves, you will make
mistakes.

Of course you will. That applies to *anything* -- if you don't know how
it works, you will make mistakes.

Given three result codes, where 0 means "no error" and an arbitrary non-
zero integer means some error, it is simple and easy to write:

failed = result_1 or result_2 or result_3

The equivalent:

failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
# or if you prefer:
succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)

are longer and more difficult to read and easier to get wrong. Even worse
are tricks like this:

failed = (result_1 + result_2 + result_3) != 0

This obscures the fact that the result codes are flags and makes it seem
like (flag + flag) is meaningful.

--
Steven

Luis Zarrabeitia

unread,
Jul 17, 2009, 10:19:51 AM7/17/09
to pytho...@python.org
On Friday 17 July 2009 07:06:26 am Jean-Michel Pichavant wrote:
>
> I was saying that using boolean operators with object instead of boolean
> values is error prone, cause no language behaves he same way,

I don't know of many languages that actively promote the duck typing concept,
are as highly dynamic as python, have the "metaclass" concept, treats almost
all language concepts as first class citizens (including functions and
classes), and so on. And don't get me started on assignment (which I consider
very natural, by the way, but apparently most of the popular languages have
pretty unnatural assignments).

It is error prone if you are expecting the result to be a bool instead of just
behaving like one (it is certainly unexpected, but you shouldn't be expecting
to get an instance of certain class anyway, for most of python's operations).
And it is confusing if you are reading the "int(inputVar) or 25" line and
have no idea of what it means (but once you know it, it becomes very
readable, almost plain english).

> and all
> behaviors are conventions difficult to figure out without diving deeply
> into the documentation (or being explained as it happened to me).

That happens with many new concepts. Welcome to python, I guess... if you are
willing to shake some of your expectations from previous programming
languages, you will enjoy it. My [little] experience teaching python tells me
that "duck typing", "non-enforced encapsulation" and "everything is an
object" are the hardest to accept for the C# folk at my faculty, but once
past it, they (the few of them who don't leave the course after that) really
enjoy the language.

> I think the initialization trick is an error, because I don't want
> foo(0) to set daysInAdvance to 25. I'll want it to set the attribute to
> 0, cause 0 is a valid integer. 0 is a valid integer content, None
> wouldn't be a valid integer content.

Well, that wouldn't be a problem with "or", but with the programmer.

The exact same behaviour could be obtained with

if int(inputValue) == 0:
inputValue = 25

and no "or" involved.

However, using only

inputValue = inputValue or 25

could have been an error if you only wanted 25 in case inputValue is None.

(the "or trick" implies certain trust in that the object you have in hand has
a reasonable definition of truth value).

--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie

Jean-Michel Pichavant

unread,
Jul 17, 2009, 10:34:57 AM7/17/09
to pytho...@python.org
Steven D'Aprano wrote:
> On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:
>
>
> Given three result codes, where 0 means "no error" and an arbitrary non-
> zero integer means some error, it is simple and easy to write:
>
> failed = result_1 or result_2 or result_3
>
> The equivalent:
>
> failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
> # or if you prefer:
> succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)
>
>
[snip]

This is, I guess, where we disagree. I find the second proposal less
error prone, and universally understandable unlike the first one. It may
be verbose, it may look even lame to some people, but in the end this is
perfectly reliable, because you manipulate only False or True within the
boolean operations.

The first form does not clearly show what is the failed criteria. It
just happens by coincidence that in this case the failed criteria
matches the Nothingness of result_1, result_2, result_3. What if results
may be 'OK' or 'KO'.

failed = result_1 or result_2 or result_3

won't work.

failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is
lame but reliable.


JM

Ethan Furman

unread,
Jul 17, 2009, 10:51:05 AM7/17/09
to pytho...@python.org
Jean-Michel Pichavant wrote:

> Steven D'Aprano wrote:
>
>> On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:
>>
>>
>> Given three result codes, where 0 means "no error" and an arbitrary non-
>> zero integer means some error, it is simple and easy to write:
>>
>> failed = result_1 or result_2 or result_3
>>
>> The equivalent:
>>
>> failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
>> # or if you prefer:
>> succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)
>>
>>
>
> [snip]
>
> This is, I guess, where we disagree. I find the second proposal less
> error prone, and universally understandable unlike the first one.

Careful! The very few (if any) things in this world that can be
considered "universally understandable" do *not* include any programming
language! :)

> It may
> be verbose, it may look even lame to some people, but in the end this is
> perfectly reliable, because you manipulate only False or True within the
> boolean operations.
>
> The first form does not clearly show what is the failed criteria. It
> just happens by coincidence that in this case the failed criteria
> matches the Nothingness of result_1, result_2, result_3. What if results
> may be 'OK' or 'KO'.

As the programmer, particularly a Python programmer, you should be
taking advantage of Python's strengths, of which this is one. If, as
you say, some function uses a "something" value to indicate an
undesirable result, then you have to use something akin to your last
statement.


~Ethan~

>
> failed = result_1 or result_2 or result_3

Steven D'Aprano

unread,
Jul 17, 2009, 11:30:11 AM7/17/09
to
On Fri, 17 Jul 2009 16:34:57 +0200, Jean-Michel Pichavant wrote:

> Steven D'Aprano wrote:
>> On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:
>>
>>
>> Given three result codes, where 0 means "no error" and an arbitrary
>> non- zero integer means some error, it is simple and easy to write:
>>
>> failed = result_1 or result_2 or result_3
>>
>> The equivalent:
>>
>> failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0) # or if
>> you prefer:
>> succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)
>>
>>
> [snip]
>
> This is, I guess, where we disagree. I find the second proposal less
> error prone, and universally understandable unlike the first one. It may
> be verbose, it may look even lame to some people, but in the end this is
> perfectly reliable, because you manipulate only False or True within the
> boolean operations.

Because it is verbose, it is more error-prone. The more code you have to
write, the more opportunities you have to make mistakes.

(This holds up to a point, beyond which being more and more terse also
leads to more errors.)

Boolean algebra is notorious for programmer errors. The more complicated
the boolean expression, the more often programmers get it wrong. The more
book-keeping they have to do, the easier it is to get it wrong. All those
(result != 0) comparisons are mere book-keeping, they don't add anything
to the code except to force the flag to be True or False.

> The first form does not clearly show what is the failed criteria.

Of course it does: at least one of the three result codes is non-zero. As
a bonus, failed will be assigned the first non-zero result code (if any).

Your preferred form, on the other hand, folds all the possible error
codes into True, throwing away useful information:

>>> result_1 = 0 # success
>>> result_2 = 0
>>> result_3 = 15 # failure
>>> failure = result_1 or result_2 or result_3
>>> failure
15
>>> failure = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
>>> failure
True

> It
> just happens by coincidence that in this case the failed criteria
> matches the Nothingness of result_1, result_2, result_3. What if results
> may be 'OK' or 'KO'.

Obviously the test you write depends on the data you have to work with.
Do you think that's surprising?


> failed = result_1 or result_2 or result_3 won't work.

Not in the example you gave, no. Although if I had to work with lots and
lots of strings of the form 'OK' and 'KO', I'd consider sub-classing
string:

>>> class OKString(str):
... def __nonzero__(self):
... if self == 'OK': return True
... elif self == 'KO': return False
... else:
... raise ValueError('invalid result code')
...
>>>
>>> a = OKString('OK')
>>> b = OKString('KO')
>>> c = OKString('KO')
>>> if a and b and c:
... print "Success!"
... else: print "Failed!"
...
Failed!


(I wouldn't bother if I only needed one or two such tests, but if I had
lots of them, I'd consider it.)


> failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is
> lame but reliable.


Yes, it's reliably complicated, reliably easy to get wrong, reliably
harder to read, and it reliably throws away information.

But apart from those disadvantages, it does the job you want it to do.


--
Steven

Emile van Sebille

unread,
Jul 17, 2009, 12:55:39 PM7/17/09
to pytho...@python.org
On 7/17/2009 7:34 AM Jean-Michel Pichavant said...

> Steven D'Aprano wrote:
>> On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:
>>
>>
>> Given three result codes, where 0 means "no error" and an arbitrary non-
>> zero integer means some error, it is simple and easy to write:
>>
>> failed = result_1 or result_2 or result_3
>>
>> The equivalent:
>>
>> failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
>> # or if you prefer:
>> succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)
>>
>>
> [snip]
>
> This is, I guess, where we disagree. I find the second proposal less
> error prone, and universally understandable unlike the first one. It may
> be verbose, it may look even lame to some people, but in the end this is
> perfectly reliable, because you manipulate only False or True within the
> boolean operations.
>
> The first form does not clearly show what is the failed criteria. It
> just happens by coincidence

No -- it happens by design because the premise is 'where 0 means "no
error" and an arbitrary non-zero integer means some error'.

> that in this case the failed criteria
> matches the Nothingness of result_1, result_2, result_3. What if results
> may be 'OK' or 'KO'.

Which by definition won't happen for the example cited...

>
> failed = result_1 or result_2 or result_3

> won't work.

... so you certainly wouldn't write a test that couldn't properly
determine success or failure.

>
> failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is
> lame but reliable.

In this case I'd write something that meets the specs of the problem
your addressing...

failed = 'KO' in (result_1,result_2,result_3)

Emile


Dr. Phillip M. Feldman

unread,
Jul 17, 2009, 9:09:37 PM7/17/09
to pytho...@python.org

Suppose that 'xor' returns the value that is true when only one value is
true, and False otherwise. This definition of xor doesn't have the standard
associative property, that is,

(a xor b) xor c

will not necessarily equal

a xor (b xor c)

To see that this is the case, let a= 1, b= 2, and c= 3.

(a xor b) xor c

yields 3, while

a xor (b xor c)

yields 1. So, I'd prefer an xor operator that simply returns True or False.

Phillip


MRAB-2 wrote:
>
>
> <snip>
>
> What values should 'xor' return? IMHO, if only one of the values is true
> then it should return that value, otherwise it should return False.
>
> 1 xor 0 => 1
> 0 xor 2 => 2
> 1 xor 2 => False
> 0 xor 0 => False
>
> This is because it's a Boolean operator, so it should fall back to
> Boolean values when necessary, like 'not':
>
> not 0 => True
> not 1 => False
>
> Also:
>
> x and y and z => (x and y) and z
> x or y or z => (x or y) or z
>
> therefore:
>
> x xor y xor z => (x xor y) xor z
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

--
View this message in context: http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24543805.html
Sent from the Python - python-list mailing list archive at Nabble.com.

Mark Dickinson

unread,
Jul 18, 2009, 5:50:06 AM7/18/09
to
On Jul 17, 12:06 pm, Jean-Michel Pichavant <jeanmic...@sequans.com>
wrote:

> I was saying that using boolean operators with object instead of boolean
> values is error prone,

I agree with this to some extent. After all, Python conditional
expressions were eventually introduced in response to buggy uses of
the 'a and b or c' idiom. See PEP 308, and:

http://mail.python.org/pipermail/python-dev/2005-September/056546.html

In my own code, I'm finding myself increasingly using conditional
expressions where I would once have used 'and' or 'or':

daysInAdvance = int(inputVar) if inputVar is not None else 0

--
Mark

Ethan Furman

unread,
Jul 20, 2009, 6:34:28 PM7/20/09
to pytho...@python.org
[fixed for bottom-posting]

You are, of course, free to write your version however it makes sense to
you and your team. :)

Since the 'and' and 'or' already return objects (and objects evaluate to
true or false), then 'xor' should behave likewise, IMO. I expect that
would be the case if it were ever added to the language.

~Ethan~

Mark Dickinson

unread,
Jul 21, 2009, 4:51:50 AM7/21/09
to

I'm not so sure. Did you ever wonder why the any() and all()
functions introduced in 2.5 return a boolean rather than returning
one of their arguments? (I did, and I'm still not sure what the
answer is.)

Mark

Ethan Furman

unread,
Jul 21, 2009, 11:34:19 AM7/21/09
to pytho...@python.org


Very good question -- I likewise do not know the answer. I will only
observe that any() and all() are functions, while 'and' and 'or' are
not. If one wanted the object-returning behavior one could string
together 'or's or 'and's instead.

~Ethan~
--
Thinking out loud here -- YMMV. :)

Albert van der Horst

unread,
Jul 25, 2009, 1:27:52 PM7/25/09
to
In article <mailman.3164.1247670...@python.org>,
Jean-Michel Pichavant <jeanm...@sequans.com> wrote:
>Christian Heimes wrote:
>> Chris Rebert wrote:
>>
>>> Using the xor bitwise operator is also an option:
>>> bool(x) ^ bool(y)
>>>
>>
>> I prefer something like:
>>
>> bool(a) + bool(b) == 1
>>
>> It works even for multiple tests (super xor):
>>
>> if bool(a) + bool(b) + bool(c) + bool(d) != 1:
>> raise ValueError("Exactly one of a, b, c and d must be true")
>>
>> Christian
>>
>>
>While everyone's trying to tell the OP how to workaround the missing xor
>operator, nobody answered the question "why is there no xor operator ?".

>
>If the question was "Why is there no 'or' operator ?", would "because A
>or B <=> not(not A and not B)" be a proper answer ?

No. I think it is because and/or can be extended to be sensible
in a context where objects can be used. (What others have expressed
as having short-circuit evaluation. So sce indeed is the underlying
reason that and/or can be extended sensibly to objects.)

Remains whether we need an xor that only works and requires that
both operands are booleans. That one we have already!
It is called != .

(a!=b)!=c
and
a!=(b!=c)

are the same for booleans, so can indeed be expressed
a!=b!=c (associativy of xor)

>
>JM
>
Groetjes Albert

--
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

Terry Reedy

unread,
Jul 25, 2009, 1:30:54 PM7/25/09
to pytho...@python.org
Albert van der Horst wrote:

> Remains whether we need an xor that only works and requires that
> both operands are booleans. That one we have already!
> It is called != .
>
> (a!=b)!=c
> and
> a!=(b!=c)
>
> are the same for booleans, so can indeed be expressed
> a!=b!=c (associativy of xor)

Not in Python

>>> a,b,c = True, False, True
>>> (a!=b)!=c
False
>>> a!=(b!=c)
False
>>> a!=b!=c
True
>>> (a!=b) and (b!=c)
True

In Math and Python, a<b<c means a<b and b<c, not (a<b)<c or a<(b<c).
!= is a comparison operator like <, not an arithmetic operator like +
(or logical xor). If one has 0/1 or True/False values, we have
arithmetic xor already, ^, which works as expected.

>>> (a^b)^c
False
>>> a^b^c
False

Terry Jan Reedy

Delaney, Timothy (Tim)

unread,
Jul 26, 2009, 8:53:33 PM7/26/09
to pytho...@python.org
Mark Dickinson wrote:

>> Since the 'and' and 'or' already return objects (and objects
>> evaluate to true or false), then 'xor' should behave likewise, IMO.
>> I expect that would be the case if it were ever added to the
>> language.
>
> I'm not so sure. Did you ever wonder why the any() and all()
> functions introduced in 2.5 return a boolean rather than returning
> one of their arguments? (I did, and I'm still not sure what the
> answer is.)

Consider the case of any() and all() operating on an empty iterable.
What type should they return?

It is impossible in the case of any() and all() to always return one of
the elements due to this edge case. Similarly, it is impossible in all
cases for a boolean xor to return one of the arguments - if both
arguments evaluate to a true (Something) value, xor must return a false
(Nothing) result.

Tim Delaney

greg

unread,
Jul 26, 2009, 9:12:26 PM7/26/09
to
Terry Reedy wrote:

> In Math and Python, a<b<c means a<b and b<c, not (a<b)<c or a<(b<c).
> != is a comparison operator like <,

Although Python extends the chaining principle to
!=, this is somewhat questionable, because
a < b and b < c implies a < c, but a != b and
b != c does not imply a != c.

I'm not sure I've ever seen a mathematician
write a != b != c, but if I did, I would tend
to think he meant to say that none of a, b,
c are equal to any other. That's not what it
means in Python, though.

--
Greg

Terry Reedy

unread,
Jul 27, 2009, 2:05:55 AM7/27/09
to pytho...@python.org

However, == is transitive, and a == b == c is quite common.
It would hardly do to have different rules for !=.

Either we have a uniform rule for a compare_op b compare_ob c, as we do,
or we have several fussy rules that would be hard to remember.

Mark Dickinson

unread,
Jul 27, 2009, 5:12:16 AM7/27/09
to
On Jul 27, 1:53 am, "Delaney, Timothy (Tim)" <tdela...@avaya.com>
wrote:

> Mark Dickinson wrote:
> >> Since the 'and' and 'or' already return objects (and objects
> >> evaluate to true or false), then 'xor' should behave likewise, IMO.
> >> I expect that would be the case if it were ever added to the
> >> language.
>
> > I'm not so sure.  Did you ever wonder why the any() and all()
> > functions introduced in 2.5 return a boolean rather than returning
> > one of their arguments?  (I did, and I'm still not sure what the
> > answer is.)
>
> Consider the case of any() and all() operating on an empty iterable.
> What type should they return?
>
> It is impossible in the case of any() and all() to always return one of
> the elements due to this edge case.

Yes, of course; the alternative implementation I was thinking of
was the one that I implemented eons ago for my own pre-2.5 code,
where I defined any and all roughly as:

any([x1, x2, x3, ...]) <-> False or x1 or x2 or x3 or ...
all([x1, x2, x3, ...]) <-> True and x1 and x2 and x3 and ...

At the time this seemed like the obvious choice, so I was a bit
surprised when it was chosen to always return a bool instead in
the official versions.

Now that I'm older and wise^H^H^H^H, well, maybe just older, the
pure bool version seems cleaner and less error-prone, even if
it's mildly inconsistent with the behaviour of and and or.

Mark

0 new messages