any() and all() on empty list?

Steve R. Hastings steve at hastings.org
Sat Apr 1 03:38:08 EST 2006


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"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list