[Tutor] True/False evaluations?

Kent Johnson kent37 at tds.net
Wed Dec 1 13:51:28 CET 2004


Liam Clarke wrote:
> Hi all, 
> 
> Got myself in a twist around logic of functions, I'll show you what I mean.
> It's  y() not being False (or True), but evaluating as true for 'if
> not y()' which gets me, as I thought that [], 0, None, False, & {} all
> evaluated the same.

As you have discovered, an empty list is not the same as False, but it evaluates to False in 
conditionals. One way to think of it is, when you evaluate a conditional, the result is coerced to a 
boolean value. Numeric zeros and empty collections are coerced to False; everything else is True.
 >>> [] is False
False
 >>> bool([]) is False
True

A list with elements in it is not an empty list, even if the elements themselves are empty. For 
example, a list containing None is different from an empty list, and its boolean value is True:
 >>> len( [None] )
1
 >>> [None] == []
False
 >>> bool( [None] )
True

If you have some math background, it might help to think of the difference between the empty set 
(which is empty) and the set containing the empty set (which is not empty, it has one member).

> 
> General query however -
> So, as k() returns a tuple, it's not false, even though the tuple
> contains two zero values. Is there a way I could do something like?
> 
> for item in k():
>       if not item: 
>          #do something
> 
> on one line? i.e. check for true/false of any value returned by  k(),
> whether it be a 2 or 20 digits long tuple

 >>> if reduce(lambda x, y: x or y, [ [], 1, None ]):
...   print 'do something'
... else:
...   print 'nothing to do'
...
do something

 >>> if reduce(lambda x, y: x or y, [ [], 0, None ]):
...   print 'do something'
... else:
...   print 'nothing to do'
...
nothing to do

lambda x, y: x or y
just gives us a function that applies logical or to its arguments.

reduce() uses the given function as an accumulator. So the whole expression is roughly equivalent to
[] or 0 or None

Kent


More information about the Tutor mailing list