bool evaluations of generators vs lists

Josh Dukes josh.dukes at
Tue Feb 10 21:50:02 CET 2009

> 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 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
-------------- next part --------------
A non-text attachment was scrubbed...
Type: text/x-python
Size: 485 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list