473,320 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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
59 8695
Steve R. Hastings wrote:
On Fri, 31 Mar 2006 16:29:00 -0800, Paul Rubin wrote:
I think "S and all(S)" is the right way to express that, if that's
what's intended.


I still would like a standard function, because "S and all(S)" does not
work with iterators. I proposed one possible function, truecount(S), that
returns a tuple of how many were true and how many there were total. Then
you could do

true_count, count = truecount(S)

if count and true_count == count:
# nonempty list and all are true
And S could be an iterator or generator function expression.

You can easily write your own truecount() but it would be nice to have
something like that as standard. I don't much like the name "truecount"
though; I'm open to suggestions for a better name.


How about:

countall(S, value=True)
Considering len() is used to get a length, and countall() is related to
all(), but it's explicit about what it's counting and would not return
True on an empty set. I think it would be useful.

true_count, count = countall(S), len(S)

Cheers,
Ron

Apr 1 '06 #51
Ron Adam <rr*@ronadam.com> writes:
true_count, count = countall(S), len(S)


In general it's preferable to not rely on len being available, since
these are arbitrary iterators.
Apr 1 '06 #52
On Sat, 01 Apr 2006 02:06:29 -0600, Ron Adam wrote:
true_count, count = countall(S), len(S)


Unfortunately, this does not solve the problem.

An iterator yields its values only once. If you have an iterator "itr",
you cannot do all(itr) and then do len(itr). Whichever one you do first
will run the iterator to exhaustion.

This is why my proposed truecount() returns a tuple, with the length and
the count of true values.

Suppose you wanted, for some reason, to know how many lines in a file
start with a vowel:

vowels = frozenset("aeiouAEIOU")
f = open("a_file.txt") # note that f is an iterator
true_count, count = truecount(line[0] in vowels for line in f)
print "%d lines in file; %d start with a vowel" % (count, true_count)
Because f is an iterator, we only get one pass through the values of the
file. Because truecount() returns a tuple with two values, one pass is
enough.
--
Steve R. Hastings "Vita est"
st***@hastings.org http://www.blarg.net/~steveha

Apr 1 '06 #53
On Sat, 01 Apr 2006 00:38:08 -0800, Steve R. Hastings wrote:
my proposed truecount() returns a tuple, with the length and
the count of true values.
I never liked the name truecount(), and the more I think about it, the
less I like the function. It should either solve a very important need,
or else it should be general enough to solve multiple needs; truecount()
doesn't really do either.

I kept thinking about this, and then suddenly I remembered an idea I read
about before. I'm not sure who invented this idea, but it wasn't me.

Here is a function called "tally()". It reduces a list to a dictionary
of counts, with one key for each value from the list. The value for
each key is the count of how many times it appeared in the list.
def tally(seq, d=None):
if d == None:
d = {}

for x in seq:
if x in d:
d[x] += 1
else:
d[x] = 1
return d

This neatly replaces truecount(), and you can use it for other things as
well.

Let's revisit my example from before:
Suppose you wanted, for some reason, to know how many lines in a file
start with a vowel:

vowels = frozenset("aeiouAEIOU")
f = open("a_file.txt") # note that f is an iterator

counts = tally(line[0] in vowels for line in f)
# counts is a dict; counts.keys() == [False, True]
count_nonvowels, count_vowels = counts.values()

total = count_nonvowels + count_vowels
print "%d lines in file; %d start with a vowel" % (total, count_vowels)

--
Steve R. Hastings "Vita est"
st***@hastings.org http://www.blarg.net/~steveha

Apr 1 '06 #54
Em Sáb, 2006-04-01 Ã*s 08:35 -0800, Steve R. Hastings escreveu:
def tally(seq, d=None):
if d == None:
d = {}

for x in seq:
if x in d:
d[x] += 1
else:
d[x] = 1
return d


Two changes:
- Use "is None".
- Use "try ... except" instead of "in"

def tally2(seq, d=None):
if d is None:
d = {}
for x in seq:
try:
d[x] += 1
except KeyError:
d[x] = 1
return d

It's also faster:
from random import choice
a = []
for i in xrange(100000): .... a.append(choice([False, True]))
.... tally(a) {False: 49922, True: 50078} tally2(a) {False: 49922, True: 50078} from timeit import Timer
min(Timer(stmt='b=tally(a)', setup='from __main__ import a, tally').repeat(3, 100))
4.2756481170654297 min(Timer(stmt='b=tally2(a)', setup='from __main__ import a,

tally2').repeat(3, 100))
3.812028169631958

Maybe you don't like my version, and the gains aren't that much, but
please use "is None" instead of "== None".

Cheers,

--
Felipe.

Apr 1 '06 #55
On Sat, 01 Apr 2006 14:35:58 -0300, Felipe Almeida Lessa wrote:
Two changes:
- Use "is None".
- Use "try ... except" instead of "in"
Yes.

Maybe you don't like my version, and the gains aren't that much, but
please use "is None" instead of "== None".


Actually, I do like your version. And I try to always use "is None"
instead of "== None"; today I made a mistake about it. Thank you for your
comments.

Ideally there should be an official tally() function in some module in
Python, and then we can just use it and not worry about how to write it. :-)
--
Steve R. Hastings "Vita est"
st***@hastings.org http://www.blarg.net/~steveha

Apr 2 '06 #56
Steve R. Hastings wrote:
Here is a function called "tally()". It reduces a list to a dictionary
of counts, with one key for each value from the list. The value for
each key is the count of how many times it appeared in the list.
def tally(seq, d=None):
if d == None:
d = {}

for x in seq:
if x in d:
d[x] += 1
else:
d[x] = 1
return d
This neatly replaces truecount(), and you can use it for other things as
well.


if True in talley(S): do_somthing()

Works for me... ;-)
Cheers,
Ron


Apr 2 '06 #57
Steve R. Hastings wrote:
On Sat, 01 Apr 2006 14:35:58 -0300, Felipe Almeida Lessa wrote:
Two changes:
- Use "is None".
- Use "try ... except" instead of "in"


Yes.

Maybe you don't like my version, and the gains aren't that much, but
please use "is None" instead of "== None".


Actually, I do like your version. And I try to always use "is None"
instead of "== None"; today I made a mistake about it. Thank you for your
comments.

Ideally there should be an official tally() function in some module in
Python, and then we can just use it and not worry about how to write it. :-)


And it's a good candidate to be written in C as well.

Cheers,
Ron
Apr 2 '06 #58
Ron Adam wrote:
Steve R. Hastings wrote:

This neatly replaces truecount(), and you can use it for other things as
well.


if True in talley(S): do_somthing()

Works for me... ;-)
Cheers,
Ron


Actulley talley isn't needed for this...

if True in S: do_domething()
That's what I get for staying up way too late last night.

Cheers, Ron

Apr 2 '06 #59
>>>>> "Steve R. Hastings" <st***@hastings.org> (SRH) wrote:
[snip]
SRH> vowels = frozenset("aeiouAEIOU")
SRH> f = open("a_file.txt") # note that f is an iterator SRH> counts = tally(line[0] in vowels for line in f)
tally([line[0] in vowels for line in f])
SRH> # counts is a dict; counts.keys() == [False, True]
No guarantee about the order. It could be [True, False].
SRH> count_nonvowels, count_vowels = counts.values()


So you must use counts[False] and counts[True].

--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: pi**@vanoostrum.org
Apr 10 '06 #60

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

Similar topics

16
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. ...
3
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...
6
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...
9
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...
1
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...
6
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...
4
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...
0
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...
3
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.