> The first example is a list.  A list of length 0 evaluates to False.
> 
> The second example returns a generator object.  A generator object
> apparently evaluates to true.  Your example is not iterating of their
> values of the generator, but evaluating bool(generator_object) itself.
> My feeling is that bool(generator_object) is ambiguous so shouldn't be
> used to begin with.

I was actually aware of that (thank you, though, for trying to help).
What I was not clear on was if the boolean evaluation is a method of an
object that can be modified via operatior overloading (in the same way
+ is actually .__add__()) or not. Clearly __nonzero__ is the operator I
was curious about. Thanks for that info. 

> bool != has_values.  Check python.org for how Python determines the
> "truthiness" of an object. Generally speaking the following evaluate
> to False:
> 
>       * None 
>       * False 
>       * zero of any numeric type, for example, 0, 0L, 0.0, 0j. 
>       * any empty sequence, for example, '', (), []. 
>       * any empty mapping, for example, {}. 
>       * instances of user-defined classes, if the class defines a
>         __nonzero__() or __len__() method, when that method returns
> the integer zero or bool value False.
> 
> All other values are considered true -- so objects of many types are
> always true.

The thing I don't understand is why a generator that has no iterable
values is different from an empty list. Why shouldn't bool ==
has_value?? Technically a list, a tuple, and a string are also objects
but if they lack values they're evaluated as False. It seems to me that
a generator is an object that intends to replace lists where lazy
evaluation would be more efficent. Here is one place where that's
definitely true. 
The main reason I'm interested in this is that it improves performance
immensely over boolean evaluation of large lists (as the attached code
shows). It seems to me if I could use find a good use for it in my
experimentation that someone else might also want to do the same thing
in real-world code. 

Is there another list I should be asking these questions on?

-- 

Josh Dukes
MicroVu IT Department
#!/usr/bin/env python
from datetime import datetime

def has_values(g):
    for i in g:
        return True
    return False

print "creation time"
start=datetime.now()
print len([ x for x in range(1,10000) if not [ y for y in range(2,x/2) if not x%y]]),"values"
print "LC time:",datetime.now()-start

start=datetime.now()
print len([ x for x in range(1,10000) if not has_values( y for y in range(2,x/2) if not x%y)]),"values"
print "GE time:",datetime.now()-start


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

Reply via email to