This is a problem that I have encountered recently. Google doesn't seem to have an answer, so I bring it to good people from.
I am looking for an easy way to populate a list with function output. Something like that:
fill(random.random(), 3) #=> [0.04095623, 0.39761869, 0.46227642]
Here are other ways I've found to do this. But I am not very pleased with them, as they seem ineffective.
results = [] for x in xrange(3): results.append(random.random())
and
map(lambda x: random.random(), [None] * 3)
Suggestions?
Thanks for all the answers. I knew there was another python-esque way.
And to efficiency issues ...
$ python --version Python 2.7.1+ $ python -m timeit "import random" "map(lambda x: random.random(), [None] * 3)" 1000000 loops, best of 3: 1.65 usec per loop $ python -m timeit "import random" "results = []" "for x in xrange(3): results.append(random.random())" 1000000 loops, best of 3: 1.41 usec per loop $ python -m timeit "import random" "[random.random() for x in xrange(3)]" 1000000 loops, best of 3: 1.09 usec per loop
source share