Andy Dingley <[EMAIL PROTECTED]> wrote: > 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 ?
Whenever it's more readable. > 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? I've read this last sentence three times now and I'm still not sure to grasp it - hopefully it's friday... Care to give an example ? > 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 ? I'd say it's bad style to call a function having side effects from within a list comp. List comps have a very declarative/functional style, while side effects are clearly on the imperative side. I never took time to think about this, but IIRC I've never used list comp that way - I then use a for loop. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list