Python Forum
List of n random elements - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: List of n random elements (/thread-24846.html)



List of n random elements - medatib531 - Mar-07-2020

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?


RE: List of n random elements - menator01 - Mar-07-2020

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)



RE: List of n random elements - jefsummers - Mar-07-2020

Two questions - are you looking for random integers, or random floats? Can numbers be repeated?


RE: List of n random elements - scidam - Mar-07-2020

(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)))



RE: List of n random elements - medatib531 - Mar-07-2020

(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!


RE: List of n random elements - jefsummers - Mar-07-2020

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?