convert loop to list comprehension

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Sep 8 20:15:46 EDT 2006


Two possibile solutions:

seq = [2, 3, 1, 9]

print sum( ([i]*n for i,n in enumerate(seq)), [])

print [i for i, x in enumerate(seq) for _ in xrange(x)]

The second one is probably quite faster.

Bye,
bearophile




More information about the Python-list mailing list