[BangPypers] Truth Tests (bool)

Noufal Ibrahim noufal at nibrahim.net.in
Wed Jan 11 05:19:58 CET 2012


Gora Mohanty <gora at mimirtech.com> writes:


[...]

> 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. 

Truth testing in general is implemted using the __nonzero__ magic
method[1].

Lists don't have a __nonzero__ so the truth value is determined using
the length (as you've said) but manually doing it on something that you
don't know the type of is not usually a good idea.

Footnotes: 
[1]  http://docs.python.org/reference/datamodel.html#object.__nonzero__

-- 
~noufal
http://nibrahim.net.in

May I ask a question?


More information about the BangPypers mailing list