bool evaluations of generators vs lists
clp2 at rebertia.com
Tue Feb 10 14:38:42 EST 2009
On Tue, Feb 10, 2009 at 11:15 AM, Josh Dukes <josh.dukes at microvu.com> wrote:
> quite simply...what???
> In : bool([ x for x in range(10) if False ])
> Out: False
This evaluates the list comprehension and creates an empty list, which
is considered boolean False by Python.
> In : bool( x for x in range(10) if False )
> Out: 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