list comprehension question

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri May 8 20:39:37 EDT 2009


On Thu, 07 May 2009 13:28:10 -0400, J Kenneth King wrote:

> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:
> 
>> On Wed, 06 May 2009 09:48:51 -0400, J Kenneth King wrote:
>>
>>> Emile van Sebille <emile at fenx.com> writes:
>>> 
>>>> On 5/5/2009 9:15 AM J Kenneth King said...
>>>>
>>>>> List comprehensions can make a reader of your code apprehensive
>>>>> because it can read like a run-on sentence and thus be difficult to
>>>>> parse. The Python documentation discourages their use and I believe
>>>>> for good reason.
>>>>
>>>> Can you provide a link for this?  I'd like to see specifically what's
>>>> being discouraged, as I'd be surprised to find routine usage frowned
>>>> upon.
>>>>
>>>> Emile
>>> 
>>> http://docs.python.org/tutorial/datastructures.html#nested-list-
>> comprehensions
>>> 
>>> 
>>> "If you’ve got the stomach for it, list comprehensions can be nested.
>>> They are a powerful tool but – like all powerful tools – they need to
>>> be used carefully, if at all."
>>
>> How does this discourage the use of list comprehensions? At most, it
>> warns that complicated list comps are tricky. Complicated *anything*
>> are tricky.
> 
> They are tricky and need to be used carefully, *if at all*.
> 
> IMO this means that if there's a way to do it without a nested list
> comprehension, then that solution should be preferred.

Earlier, you claimed that list comps in general were discouraged:

"List comprehensions can make a reader of your code apprehensive because 
it can read like a run-on sentence and thus be difficult to parse. The 
Python documentation discourages their use and I believe for good reason."

Emile said "I'd be surprised to find routine usage frowned upon", giving 
you the opportunity to correct his (mis)understanding. You failed to do 
so, which I took as meaning that you agreed that routine usage of simple 
list comps were frowned upon. Now you're talking about *nested* list 
comps. You started off (apparently) objecting to list comps in general, 
because they "can" make readers apprehensive. Now you seem to be saying 
that it's only the complicated, overly-dense ones which rightly make 
readers apprehensive which you object to.

I suppose we're making progress if we agree that the Python docs warn 
against unnecessarily complicated nested list comps. Whether it 
discourages as well as warns is a matter of interpretation. But there's 
certainly no sign that list comps as a general technique are discouraged 
just because overly-complicated list comps are tricky to read. The same 
can be said about *any* piece of code.



-- 
Steven



More information about the Python-list mailing list