473,545 Members | 529 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

any() and all() on empty list?

So, Python 2.5 will have new any() and all() functions.
http://www.python.org/dev/peps/pep-0356/
any(seq) returns True if any value in seq evaluates true, False otherwise.

all(seq) returns True if all values in seq evaluate true, False otherwise.

I have a question: what should these functions return when seq is an empty
list?

Here is Guido's original article where he suggested any() and all():
http://www.artima.com/weblogs/viewpost.jsp?thread=98196

He offered this sample code for the semantics of any() and all():

def any(S):
for x in S:
if x:
return True
return False

def all(S):
for x in S:
if not x:
return False
return True

And he pointed out how nifty it is to combine generator functions with
these two new functions:
any(x > 42 for x in S) # True if any elements of S are > 42
all(x != 0 for x in S) # True if all elements if S are nonzero

I'm completely on board with the semantics for any(). But all() bothers
me. If all() receives an empty list, it will return True, and I don't
like that. To me, all() should be a more restrictive function than any(),
and it bothers me to see a case where any() returns False but all()
returns True.

In the all() example, if there *are* no values in S, then none of the
values can be != 0, and IMHO all() should return False.

Therefore, I propose that all() should work as if it were written this way:

def all(S):
ret_val = False

for x in S:
ret_val = True
if not x:
return False

return ret_val
Comments?

P.S. I searched with Google, and with Google Groups, trying to find
anyplace this might have been discussed before. Apologies if this has
already been discussed and I missed it somehow.
--
Steve R. Hastings "Vita est"
st***@hastings. org http://www.blarg.net/~steveha

Mar 29 '06 #1
59 8740
"Steve R. Hastings" <st***@hastings .org> writes:
In the all() example, if there *are* no values in S, then none of the
values can be != 0, and IMHO all() should return False.


That goes against the usual meaning of "all" in, say, mathematical logic.

Usually, "for all X in S, PRED(x) is true" means:
there does not exist X in S so that PRED(x) is false.

So, all(empty sequence) should be true.
Mar 29 '06 #2
"Paul Rubin" <http://ph****@NOSPAM.i nvalid> wrote in message
news:7x******** ****@ruckus.bro uhaha.com...
"Steve R. Hastings" <st***@hastings .org> writes:
In the all() example, if there *are* no values in S, then none of the
values can be != 0, and IMHO all() should return False.
That goes against the usual meaning of "all" in, say, mathematical logic.

Usually, "for all X in S, PRED(x) is true" means:
there does not exist X in S so that PRED(x) is false.

How do you get this "usually" stuff? I would agree that this is usually
implemented as a short-circuited loop through the list, that breaks out at
the first False value. But I would not be quick to equate "commonalit y of
implementation" with "meaning".
So, all(empty sequence) should be true.

"should be"? Or "usually turns out to be"?

To my mind, the *meaning* of all() is that every element in the list asserts
True. But this is with an initial assumption that all() is False, unless I
test every value and find them to be True. Since I assume False to begin
with, I get no values in the list to contradict the assumption, and so
all([]) returns False.

It would seem that the resolution rests on which initial condition we
choose, False or True. Perhaps we should consult a more formal mathematical
resource for this.

-- Paul
"If it was so, it might be; and if it were so, it would be; but as it isn't,
it ain't. That's logic."
Mar 29 '06 #3
[Steve R. Hastings]
So, Python 2.5 will have new any() and all() functions.
http://www.python.org/dev/peps/pep-0356/
any(seq) returns True if any value in seq evaluates true, False otherwise..

all(seq) returns True if all values in seq evaluate true, False otherwise..

I have a question: what should these functions return when seq is an empty
list?
Here, from the current development trunk, is what they _do_ return:

Python 2.5a0 (trunk:43410M, Mar 28 2006, 16:42:49) ...
Type "help", "copyright" , "credits" or "license" for more information.
any([]) False all([])

True
Here is Guido's original article where he suggested any() and all():
http://www.artima.com/weblogs/viewpost.jsp?thread=98196

He offered this sample code for the semantics of any() and all():

def any(S):
for x in S:
if x:
return True
return False

def all(S):
for x in S:
if not x:
return False
return True

...
|
I'm completely on board with the semantics for any(). But all() bothers
me. If all() receives an empty list, it will return True,
Yes.
and I don't like that.
Tough ;-)
To me, all() should be a more restrictive function than any(),
and it bothers me to see a case where any() returns False but all()
returns True.
There are deeper principles at work: so that endcases work out as
smoothly as possible, a "reduction" function applied to an empty
collection always arranges to return the identity element for the
reduction operation. This is the reason that sum([]) returns 0, for
example: 0 is the identity element for addition, meaning that x+0=x
for all x.

Other useful identities follow from this, and from the associativity
of most reduction operations. For example, sum(seq) = sum(seq[:i]) +
sum(seq[i:]) for any i >= 0, even if i is such that one (or both!) of
the slices on the right-hand side is empty. That wouldn't be true if
sum([]) were not 0, and arranging to make it true saves programmers
from having to deal with some otherwise special cases.

The reduction operation for any() is logical-or, and False is the
identity element for logical-or: x logical-or False = x for all
Boolean x.

Likewise the reduction operation for all() is logical-and, and True is
the identity element for that: x logical-and True = x for all Boolean
x.

Examples of other useful identities that follow from picking the
identity elements in the empty case, which hold even if `seq` is
empty:

any(seq) = not all(not x for x in seq)
all(seq) = not any(not x for x in seq)
In the all() example, if there *are* no values in S, then none of the
values can be != 0, and IMHO all() should return False.
That would break everything mentioned above. Think of it another way:
if all(seq) is false, shouldn't it be the case that you can point to
a specific element in seq that is false? After all (pun intended
;-)), if it's not the case that all x in seq are true, it must be the
case that some x in seq is false. But if seq is empty, there is no x
in seq that's either true or false, and in particular there's no x in
seq that's false. Since we can't exhibit an x in seq such that x is
false, saying that all(seq) is false would be very surprising to you
on some other day ;-)
Therefore, I propose that all() should work as if it were written this way:

def all(S):
ret_val = False

for x in S:
ret_val = True
if not x:
return False

return ret_val
Comments?


That won't happen, for three reasons: several were given above; this
is also the convention used for universal and existential quantifiers
applied to empty sets in mathematical logic (and for much the same
reasons there); and it matches prior art in the ABC language (which is
one of Python's predecessors, and which had direct syntactic support
for universal and existential quantifiers in Boolean expressions).
Mar 29 '06 #4
"Steve R. Hastings" <st***@hastings .org> writes:
So, Python 2.5 will have new any() and all() functions.
http://www.python.org/dev/peps/pep-0356/
And there was much rejoicing.
any(seq) returns True if any value in seq evaluates true, False otherwise.
Yep.
all(seq) returns True if all values in seq evaluate true, False otherwise.
Not quite how I'd phrase it. I prefer, for symmetry with 'any':

all(seq) returns False if any value in seq evaluates false, True otherwise.
I have a question: what should these functions return when seq is an
empty list?

Here is Guido's original article where he suggested any() and all():
http://www.artima.com/weblogs/viewpost.jsp?thread=98196

He offered this sample code for the semantics of any() and all():

def any(S):
for x in S:
if x:
return True
return False

def all(S):
for x in S:
if not x:
return False
return True
I love the symmetry of these semantics, find them quite intuitive, and
therefore disagree with your interpretation of 'all()'.
I'm completely on board with the semantics for any(). But all() bothers
me. If all() receives an empty list, it will return True, and I don't
like that. To me, all() should be a more restrictive function than any(),
and it bothers me to see a case where any() returns False but all()
returns True.


-1.

You may as well argue that "any() should be a more restrictive
function than all(), and it bothers me to see a case where all()
returns False but any() returns True."
It seems clear to me that an empty argument list fails a check for
"any True?", because that's the same as a check for "all False?". The
only reasonable alternative would be a special case for an empty
argument list, and that's too ugly.

It seems clear to me that an empty argument list passes a check for
"all True?", because that's the same as a check for "any False?". The
only reasonable alternative would be a special case for an empty
argument list, and that's too ugly.

To imagine that one of these "should be a more restrictive function"
would belie their simple, elegant, and (to me) obvious definitions. I
disagree with your interpretation.

--
\ "My house is made out of balsa wood, so when I want to scare |
`\ the neighborhood kids I lift it over my head and tell them to |
_o__) get out of my yard or I'll throw it at them." -- Steven Wright |
Ben Finney

Mar 29 '06 #5
"Steve R. Hastings" <st***@hastings .org> wrote in message
news:pa******** *************** *****@hastings. org...
So, Python 2.5 will have new any() and all() functions.
http://www.python.org/dev/peps/pep-0356/
any(seq) returns True if any value in seq evaluates true, False otherwise.

all(seq) returns True if all values in seq evaluate true, False otherwise.

I have a question: what should these functions return when seq is an empty
list?

Here is my attempt at a more formal approach to this question, rather than
just using our intuition. Unfortunately, following this process proves my
earlier post to be wrong, but, oh well...

Consider two sets A and B where A+B is the union of the two sets.

if any(A+B) = True -> any(A) or any(B) = True
but we cannot assert either any(A)=True or any(B)=True.

if any(A+B) = False -> any(A) = False and any(B) = False.
if all(A+B) = True -> all(A)=True and all(B)=True
if all(A+B) = False -> all(A)=False or all(B)=False
but we cannot assert either all(A)=False or all(B)=False.
Now instead of B, lets add the empty set 0 to A. We want to come up logic
such that adding the empty set does not change the values of all() or any(),
since A+0=A.

any(A+0) = any(A) or any(0)

any(0) must be False, so that if any(A) is True, any(A+0) is True, and if
any(A) is False, any(A+0) is False.

all(A+0) = all(A) and all(0)

if all(A) is True, all(A+0) is True.
Therefore, all(0) is True.

-- Paul
Mar 29 '06 #6
Thank you very much for explaining this. And so thoroughly!

Of course I withdraw all objections. :-)
--
Steve R. Hastings "Vita est"
st***@hastings. org http://www.blarg.net/~steveha

Mar 29 '06 #7
"Paul McGuire" <pt***@austin.r r._bogus_.com> writes:
Usually, "for all X in S, PRED(x) is true" means:
there does not exist X in S so that PRED(x) is false.

How do you get this "usually" stuff? I would agree that this is usually
implemented as a short-circuited loop through the list, that breaks out at
the first False value. But I would not be quick to equate "commonalit y of
implementation" with "meaning".


See <http://en.wikipedia.or g/wiki/For_all>:

Generally, then, the negation of a propositional function's universal
quantification is an existential quantification of that propositional
function's negation; symbolically,

\lnot\ \forall{x}{\in} \mathbf{X}\, P(x) \equiv\
\exists{x}{\in} \mathbf{X}\, \lnot\ P(x)
Mar 29 '06 #8
Paul McGuire enlightened us with:
That goes against the usual meaning of "all" in, say, mathematical
logic.

Usually, "for all X in S, PRED(x) is true" means: there does not
exist X in S so that PRED(x) is false.
How do you get this "usually" stuff?


From its mathematical definition.
I would agree that this is usually implemented as a short-circuited
loop through the list, that breaks out at the first False value.
Implementation is irrelevant when it comes to the definition of a
mathematical operator.
But I would not be quick to equate "commonalit y of implementation"
with "meaning".
Which is good.
Perhaps we should consult a more formal mathematical resource for
this.


In mathematics, 'for all x in A, f(x) is True' is true when A is
empty. You can either look it up on trust someone who studied
mathematics (me) on it.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Mar 29 '06 #9
Paul McGuire wrote:
"Paul Rubin" <http://ph****@NOSPAM.i nvalid> wrote in message
news:7x******** ****@ruckus.bro uhaha.com... To my mind, the *meaning* of all() is that every element in the list asserts
True. But this is with an initial assumption that all() is False, unless I
test every value and find them to be True. Since I assume False to begin
with, I get no values in the list to contradict the assumption, and so
all([]) returns False.


Looking at in a different way... If we consider also having a function
none() (for comparison), would it be consistent with all()?

def none(S):
for x in S:
if x: return False
return True
any([]) -> False

none([]) -> True (same as 'not any(S)')

all([]) -> True ? False
I think I agree that all() should have an initial presumption of being
False.
Looking at it in yet another way... (yes, not as efficient)

def all(S):
S_ = [x for x in S if x]
return S_ == S

def any(S):
S_ = [x for x in S if x]
return S_ != []

def none(S):
S_ = [x for x in S if x]
return S_ == []
In this view and empty set can be True for all(). Is it posible
'all([])' is undefined? Here, none() and all() return contradicting
values. So maybe the correct version may be...

def all(S):
if S == []: return False
for x in S:
if x return True
return False

I think a few valid actual use case examples could clear it up. What
makes the most sense?

Cheers,
Ron

Mar 29 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
1970
by: Ajay | last post by:
Hi all, i want to know when i create a class.what all it contains.I know the following things are there by default if i do not declare them by myself.Please tell the other things that are left. 1. constructor 2.Destructor 3.Copy constructor 4. Assignment operator
3
1855
by: rGenius | last post by:
hi all, im planning to create a lookup usercontrol where i need to specify a custom property (a form) to be loaded up once a button is pressed. usercontrol contains: textbox button now how can i create a variable in my usercontrol to list all forms in
6
2915
by: Lisa | last post by:
I am reading in data from a text file. I want to enter each value on the line into a list and retain the order of the elements. The number of elements and spacing between them varies, but a typical line looks like: ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' Why does the following not work: line = ' SRCPARAM 1...
9
2671
by: | last post by:
I am interested in scanning web pages for content of interest, and then auto-classifying that content. I have tables of metadata that I can use for the classification, e.g. : "John P. Jones" "Jane T. Smith" "Fred Barzowsky" "Department of Oncology" "Office of Student Affairs" "Lewis Hall" etc. etc. etc. I am wondering what the efficient way...
1
1401
by: Tzury Bar Yochay | last post by:
while I can invoke methods of empty string '' right in typing (''.join(), etc.) I can't do the same with empty list example: I would not use b = a since I don't want changes on 'b' to apply on 'a'
6
2235
by: =?Utf-8?B?SFJzb2Z0IEluZm9ybcOhdGljYQ==?= | last post by:
I Have a page (clientes.aspx), inside a masterpage I have some textbox, and when the user clicks the button 'Cancel', I need to empty all controls. I tried this, with runtine error: For Each txtControl As TextBox In Me.Controls txtControl.Text = "" Next error message in runtime: can't convert as object of type 'ASP.masterpage_master' in...
4
1404
by: Hill | last post by:
I want a class Table which saves one list of Pair<int,std::string>. And I want that it has following behaviour: Table t;//now t is empty try{ int i = t;// I want this call to an empty table will throw a exception } catch(...){ std::cout << "It's a empty table,bad operator" << std::endl;
0
1727
by: Hans Kesting | last post by:
Hi, I want to edit an entire list on a single page, say a shopping list where every 'item' consists of a name and an amount. I don't know beforehand how many items will be needed. Using a Repeater I can put a list of textboxes on the screen and fill them with the (previously) stored list. After a click on a "save" button I can read...
3
1524
by: geraldjr30 | last post by:
hi, i managed to reset the $_GET to $_POST passed from previous page, but for some reason when i type in a in the form it resets back to all. i do not want this to happen... can someone look at my code and tell me how to prevent this? <html> <STYLE type="text/css"> TD{font-family:ARIAL;font-size:11px;color:#666666;}
0
7465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5969
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
701
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.