list comprehension question

J Kenneth King james at agentultra.com
Thu May 7 13:28:10 EDT 2009


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.

>> and
>> 
>> "In real world, you should prefer builtin functions to complex flow
>> statements."
>
> That's ridiculous. The example given is a special case. That's like 
> saying "Loops are hard, so in the real world, if you want a loop, find a 
> builtin function that does what you want instead."
>
> What's the "builtin function" we're supposed to prefer over a "complex 
> flow statement" like this?

It's not ridiculous and says nothing of the sort.  You're jumping to
conclusions.  If you have a problem with it, I suggest you complain to
the Python documentation people.  I don't make this stuff up.

Just look at many of the example solutions provided in this thread to
the OP's problem. The examples in the link I provided are also good as
are ones provided in the itertools documentation.

Keep in mind that nested comprehensions are still available because
they do have a use case that justifies their existence. However, I
think the Python documentation warns against their use because people
might rely on them for problems where they aren't necessary and since
they are difficult to read... it can lead to difficult to read code.



More information about the Python-list mailing list