list comprehension

Andy Dingley <dingbat@codesmiths.com> dingbat at codesmiths.com
Fri Jun 30 08:46:46 EDT 2006


Simon Forman wrote:

> There's more to it, but that's the basic idea.

This much I knew, but _why_ and _when_ would I choose to use list
comprehension (for good Python style), rather than using a simple
"traditional" loop ?

If I want to generate something that's simply ( [1] + [2] + [3]+... )
then list comprehension is obviously the tool of choice. I suspect
though that there's more to it than this. Is list comprehension also
treatable as a sneaky concise formulation for nested lists, where
they're as much about selection of individual elements, so much as
concatenation of the sequence?

What happens if a comprehension has side effects, such as from calling
a function within it? Is this regarded as good or bad coding style? Is
it evil (as structured programming would claim) or is it  a concise
formulation for an iterator or visitor pattern ?




More information about the Python-list mailing list