Python Forum

Full Version: List of n random elements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I need to make a list of 10 random numbers. A simple way is the following

from random import random
newlist = []
for i in range(10):
    newlist.append(random())
I was looking to make it more elegant (e.g. without using variable i).
I thought something like

newlist2 = [random()]*10
but this of course makes the same numbers. Is there any other way?
from random import randint
random_numbers = []

for i in range(9):
    random_numbers.append(randint(0,9))

print(random_numbers)

Another way

from random import randint
rn =[randint(0,9) for i in range(9)]
print(rn)
Two questions - are you looking for random integers, or random floats? Can numbers be repeated?
(Mar-07-2020, 01:32 AM)medatib531 Wrote: [ -> ]I was looking to make it more elegant (e.g. without using variable i).
If you are looking for a way to do this without declaring an auxiliary variable, you can use map, e.g.

list(map(lambda x: random(), range(10)))
(Mar-07-2020, 04:38 AM)jefsummers Wrote: [ -> ]Two questions - are you looking for random integers, or random floats? Can numbers be repeated?

So random() is just a placeholder, in my program it is an object that creates different instances. Of course I don't want to copy 1 object 10 times but create 10 different instances of it.

(Mar-07-2020, 08:21 AM)scidam Wrote: [ -> ]
(Mar-07-2020, 01:32 AM)medatib531 Wrote: [ -> ]I was looking to make it more elegant (e.g. without using variable i).
If you are looking for a way to do this without declaring an auxiliary variable, you can use map, e.g.

list(map(lambda x: random(), range(10)))
Yes getting rid of the unused variable is nice, thanks!
Quote:So random() is just a placeholder, in my program it is an object that creates different instances. Of course I don't want to copy 1 object 10 times but create 10 different instances of it.

That's really a different question. Are you asking how to create a list of 10 instances of a class?