list comprehensions *are* nice

Andrew Dalke dalke at acm.org
Mon May 14 06:24:26 EDT 2001


A couple months ago I complained that list comprehensions were
too confusing and that I would still be using

   results = []
   for val in data:
     results.append(..some.expression.using.val..)

I was wrong.

I've been messing around with list comprehensions on non-client
code and found them quite addictive.  On client code I just
needed to write some regression code which looked like

   names = []
   for compound in results.selected_compounds:
     names.append(compound["smiles"])

I used it about 1/2 a dozen times, so replaced it with a
function.  Sometimes the "smiles" is replaced with "NAME",
so the function is used like

   names = get_list_item(results.selected_compounds)

However, while less code and enabling reuse, I don't find this
function name very descriptive, and couldn't think of anything
better.  So it ends up being a black block and hinders understanding.

With list comprehensions I would use

names = [compound["smiles"] for compound in results.selected_compounds]

This is a longer than using a function and only a bit shorter
(measured in number of characters to type) than the original 3-line
solution.  But it make the whole code eaiser to understand.

I think it's because of three reasons:
  1) everything is visible at once, so I don't need to remember how
       a function is implemented

  2) the pattern of the list comprehension syntax for expressions as
       small as this is easy to learn, so I don't really read the
       code but just pick out the useful parts

  3) the code is 1 line instead of 3, which lets me see more of its
       context.  (I do miss my 21" SGI monitor :)

So I like it.  Now I need to see if my clients, who for the most
part are physical scientists by training, also find it as nice
as I do.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list