List comprehension confusion...

Andrew Dalke adalke at mindspring.com
Sat Feb 1 22:48:20 EST 2003


Afanasiy wrote:
> I am confused about the purpose of list comprehensions.
> What can they do which an explicit for loop cannot?

That are more readable and concise.  Here's a for loop
approach for a pretty frequent problem, get the "some_field"
attribute of all elements in a list

results = []
for term in data:
    results.append(term.some_field)

Here's the list comprehension solution

results = [term.data for term in data]


Much easier to see and, with only a little bit of practice,
easy to understand.

Compare that to another possible solution I've done,
which is to write a function for each of these common tasks,
trying to reduce duplicate code

def get_element_attribute(data, attr):
     results = []
     for element in data:
         results.append(getattr(element, attr))
     return results
  ...

results = get_element_attribute(data, "some_field)

Not only slower, but you end up having all these little,
tiny functions which reduce code (and hence coding errors)
at the expense of understanding.


And for bonus points, I don't have to make up an
intermediate list -- if I want the results put back
into 'data' I can do

data = [term.data for term in data]

					Andrew
					dalke at dalkescientific.com





More information about the Python-list mailing list