maze88 maze88 -4 years ago 64
Python Question

How can I generate n random numbers without a for loop

I am trying to generate 4 random integers between 0-9.
I can easily achieve this using a for-loop:

digits = [random.randrange(10) for i in range(4)]


Assuming it is possible, I was wondering about other ways to yield the same result, perhaps without directly using a for-loop. I was experimenting with itertools and this didn't work:

digits = itertools.repeat(random.randrange(10), 4)


The main purpose of my question is to expose myself to additional methods.
Thanks.

Answer Source
numpy.random.randint(0, 10, size=4)

or to use itertools

list(map(random.randrange, itertools.repeat(10, 4)))

or even

list(map(random.randrange, [10]*4))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download