Coding style

Carl Banks pavlovevidence at gmail.com
Tue Jul 18 01:13:17 EDT 2006


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


Here's another reason not to use "if lst".  Say you have a function
that looks like this:

    def process_values(lst):
        if not lst:
            return
        do_expensive_initialization_step()
        for item in lst:
            do_something_with(item)
        do_expensive_finalization_step()

That works, right?  No problem, right?

What if you called the function like this:

    process_values(x.strip() for x in values_lst)

Oops, now we've just gone through an expensive initialization and
finalization for nothing (since values_lst was empty).  Maybe some
subtle bugs introduced.  If we're lucky, the finalization step will
throw an exception.

If we had used "if len(list)>0", we'd have gotten a nice exception
telling us that a generator is not welcome.  Then we'd have changed the
argument to a list comprehension, or better, changed the function to
work for any iterator.


Carl Banks




More information about the Python-list mailing list