A more elegant way to do this list comprehension?

Gary Herron gherron at islandtraining.com
Wed Jun 7 08:21:50 CEST 2006


Levi Self wrote:
> This probably seems very trivial, maybe even a bit silly, but I was
> wondering if someone has a better list comprehension that does the
> same thing as this one:
>
> >>> print [[[i]*i for i in range(1,9)][j][k] for j in range(8) for k
> in range(j+1)]
> [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7,
> 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8]
>
> Thanks,
> Levi
Sure.  Try:
[i+1 for i in range(8) for j in range(i+1)]

Gary Herron




More information about the Python-list mailing list