comprehensions was Re: Switch statements again

Andrew Dalke adalke at mindspring.com
Thu Jan 16 13:23:32 EST 2003


Dave Brueck wrote:
> But why single out comprehensions? Isn't this true for _any_ feature/idiom
> you're not used to? I find comprehensions to be very readable, so I use
> them a lot, so I find them more readable, but IMO they were also pretty
> readable from the get-go.
> 
> In the specific case of comprehensions, I always have to "slow down" when
> reading code that instead one of the builtin functions (e.g. map, filter)
> because to me they are far less clear. I know I'm comparing syntax to a
> builtin, but given a sequence, S, the code:
> 
> [x for x in S if x > 5]
> 
> always makes far more sense to me than:
> 
> filter(lambda x: x>5, S)

I, like Shaleh, once thought that list comprehensions would be
confusing.  I, like Shaleh, changed my mind after using it for a bit.

The reason is that I wasn' sure if my target users (computational
chemists and computational biologists) could understand what

names = [x.name for x in sequences if len(x) > 5]

would do.  You compare that to filter/lambda, but the actual
comparison would be to

names = []
for x in sequences:
   if len(x) > 5:
     names.append(x)

which is easy for even someone without Python experience to
understand.

Unfortunately, I haven't worked with beginning Python programmers
since list comprehensions were added, so I haven't been able
to observe their reaction.  However, for intermediate programmers
and for me, it's not been a problem.  And it replaced code I was
writing like

def get_list_attribute(list, name):
   data = []
   for x in list:
     data.append(getattr(x, name))
   return data
...
names = get_list_attribute(list, "name")
...
charges = get_list_attribute(list, "charge")

so ended up making the code easier.

> FWIW, I found simple list comprehensions to be one of the least taxing
> Pythonisms to get used to - IMO the syntax maps very obviously to the
> behavior.

It wasn't as obvious to everyone.

					Andrew
					dalke at dalkescientific.com






More information about the Python-list mailing list