convert loop to list comprehension

bvdp at xplornet.com bvdp at xplornet.com
Sat Sep 9 12:55:12 EDT 2006


Paul Rubin wrote:
> "bvdp at xplornet.com" <bvdp at xplornet.com> writes:
> > > 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 :)
>
> I think even if you code a loop, it's still cleaner to use enumerate:
>
>
>     seq = [2, 3, 1, 9]
>     tmp = []
>     for i,a in enumerate(seq):
>         tmp.extend([i]*a)

Oh, good! Yes, cleaner ... and in my little test a tiny bit faster.
Thanks.




More information about the Python-list mailing list