convert loop to list comprehension

bvdp at xplornet.com bvdp at xplornet.com
Fri Sep 8 22:15:45 EDT 2006


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 :)

Mind you, there are some interesting bits and pieces of code in this
thread!




More information about the Python-list mailing list