bool evaluations of generators vs lists

Chris Rebert clp2 at
Tue Feb 10 14:38:42 EST 2009

On Tue, Feb 10, 2009 at 11:15 AM, Josh Dukes <josh.dukes at> wrote:
> quite simply...what???
> In [108]: bool([ x for x in range(10) if False ])
> Out[108]: False

This evaluates the list comprehension and creates an empty list, which
is considered boolean False by Python.

> In [109]: bool( x for x in range(10) if False )
> Out[109]: True

Whereas this creates a /generator object/, whose inner expression is
*not evaluated until specifically required* (e.g. by for-looping over
the generator object). Generators don't have a specially defined
truthiness critera (it's impossible to define generally -- consider
something like `x for x in all_integers if f(x)`, for a complicated
f(x), which would require a solution to the halting problem to know in
advance if it will have a non-zero length), so they end up using the
default behavior for objects with otherwise undefined boolean truth,
which is to consider them True.


Follow the path of the Iguana...

More information about the Python-list mailing list