Relying on the behaviour of empty container in conditional statements

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Tue Jul 11 15:43:57 EDT 2006


Simon Forman schreef:
> I've been programming in python for years and I've always used this
> form
> 
> if not seq:
> if seq:
> 
> rather than the other and never had any problems.
> 
> Anyone presenting arguments in favor of the len() form is IMHO, not
> "getting it".  AFAIK, python is not "smart" enough to optimize away the
> (totally unnecessary) call to len(), so the programmer should do it for
> herself.
> 
> The "pythonic" form is safe, not weird, and just as explicit.

I know that that is the consensus, and I mostly the form without len(), 
but somehow I still feel it is not as explicit. In

if seq:

there is no distinction between seq is None on the one hand and seq 
being a valid empty sequence on the other hand.

I feel that that is an import distinction, and it's the reason I find 
myself using len() from time to time (even though I can't think of a use 
case right now).



-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list