convert loop to list comprehension

Steve Holden steve at holdenweb.com
Sat Sep 9 07:26:38 EDT 2006


bvdp at xplornet.com wrote:
> Carl Banks wrote:
> 
>>bvdp at xplornet.com wrote:
>>
>>>Paul Rubin wrote:
>>>
>>>>bearophileHUGS at lycos.com writes:
>>>>
>>>>>print sum( ([i]*n for i,n in enumerate(seq)), [])
>>>>
>>>>Wow, I had no idea you could do that.  After all the discussion about
>>>>summing strings, I'm astonished.
>>>
>>>Me too ... despite what bearophile said, this is faster than the 2nd
>>>example. Nearly as fast as the original loop :)
>>
>>See if it's still faster if the original sequence is length 1000.
>>(Hint: it won't be.)  Adding lists with sum has the same performance
>>drawback that adding strings does, so it should be avoided.
>>
>>sum is for adding numbers; please stick to using it that way.
>>
>>FWIW, the original loop looked perfectly fine and readable and I'd
>>suggest going with that over these hacked-up listcomp solutions.  Don't
>>use a listcomp just for the sake of using a listcomp.
> 
> 
> Thanks for that, Carl. I think that using the loop is probably what
> I'll end up doing. I had no idea that the listcomp thing would be quite
> a complicated as it is appearing. I had it in my mind that I was
> missing some obvious thing which would create a simple solution :)
> 
Your original solution was the simplest, in that it's easy to understand 
and maintain.

> Mind you, there are some interesting bits and pieces of code in this
> thread!
> 
Right. But Python in general is designed to encourage straightforward 
expression of straightforward ideas, while retaining the ability to 
solve complex problems in innovative ways.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list