convert loop to list comprehension

Carl Banks pavlovevidence at gmail.com
Fri Sep 8 22:05:25 EDT 2006


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.


Carl Banks




More information about the Python-list mailing list