[BangPypers] Truth Tests (bool)
noufal at nibrahim.net.in
Wed Jan 11 16:13:06 CET 2012
Senthil Kumaran <senthil at uthcode.com> writes:
> On Wed, Jan 11, 2012 at 09:49:58AM +0530, Noufal Ibrahim wrote:
>> > It is not clear what you want from your description. To check if a
>> > list is empty, see if len( list ) is zero.
>> You don't want to do that. Your "list" might be a generator (unless you
>> check for type which is a bad idea anyway) and "len"ing that will
>> consume it which might be a potentially expensive operation.
> While the explaination on __nonzero__ is useful out of this context,
> how can list be a generator? I am assuming that none are confusing the
A list can't be a generator but if you write a function to receive an
iterable x and then do a len(x) to check it it's True or False, it will
work fine for lists but passing a generator this function might have
unpredictable results. That's why I'm cautioning against using `len` to
check for whether an object is empty or not.
> In practical cases for testing boolean in lists, just use the list as
> the test. Empty list is false.
Agreed. This is the right way to do it rather than using len.
Why don't you pair `em up in threes? -Yogi Berra
More information about the BangPypers