list comprehension question

Lie Ryan lie.1296 at gmail.com
Thu May 7 05:18:56 EDT 2009


Lie Ryan wrote:
> Steven D'Aprano wrote:
>>> "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.
>>
>>
>>> 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?
>>
>> # split text into word fragments of length <= 3
>> sentence = "a sentence is a series of words"
>> new = [word[i:i+3] for word in sentence.split() for i in range(0, 
>> len(word), 3)]
> 
> I often found list comprehension *more* readable than the equivalent 
> for-loop because of its density. Seeing complex for-loop requires one 
> step of thinking for each line, but in list comprehension I can skip 
> some of the steps because I know what list comprehension would roughly 
> look like.
> 
> i.e.
> 
> when I process this:
> 
> lst = []              #1
> for i in range(10):   #2
>     lst.append(i)     #3
> 
> I do 3 steps of thinking for each line
> 
> but seeing this is only one step, since I know it is going to create new 
> list (skipping step #1) and I know i will be appended to that list 
> (skipping step #3)

I don't know what I was thinking before sending that last line, here is 
what it was supposed to be:

but in list comprehension I see this in only one step, since I know it 
is going to create new list (skipping step #1) and I know 'i' will be 
appended to that list (skipping step #3) and this also continues to 
nested list comprehensions



More information about the Python-list mailing list