Coding style

Carl Banks pavlovevidence at gmail.com
Tue Jul 18 00:45:47 EDT 2006


PTY wrote:
> Which is better?
>
> lst = [1,2,3,4,5]
>
> while lst:
>   lst.pop()
>
> OR
>
> while len(lst) > 0:
>   lst.pop()

I'm going to go against general opinion and suggest using "len(lst)>0",
though this is not a good example of why I think that.

In practice, I'd say the former is less generic.  No, that's not a
typo.

If you were to write a function that expects a list (and actually uses
the list interface, indexing and such, rather than merely passing it
off to another function), the function would almost certainly fail if
you were to pass in an integer or some other non-sequence type.
However, functions expecting a list have a decent chance of working if
you were to pass in a numpy array.

But if you were to write "if lst" instead of "if len(lst)>0", then
you've just ensured your function will fail for numpy arrays.  But you
get no benefit in genericity, because non-sequence types almost
certainly wouldn't work anyways.

Therefore, the only time I'd recommend using "if lst" is if all you're
doing is passing it to other functions.


Carl Banks




More information about the Python-list mailing list