I want to generate a list with 10 random floats using a loop. Afterwards I want to print 5 of these randomly.
I have this loop:
import random
for i in range(5):
print(float(random.randint(1,10)
this gives me an output of 5 random numbers between 1-10. But is the result really random floats?
With this, I didn't really fill a list with 10 random floats did I?
for a in range(1,11,1):
print(a)
would this be better? As I understood, random.sample creates a list automatically. Is that true?
import random
a = random.sample(range(1,11),10)
print(a)
there the output would be e.g.: [1, 3, 7, 6, 9, 10, 5, 8, 4, 2]
but then it would give me just 1-10 back in a random order.
So I could change range to range(1,1000),10)
Then it would create a list with 10 random numbers only within 1 to 1000.
Is there a solution to this? I am just curious, bc if its infinite then I likely get a 10 digit number which is way too long.
If I want to choose 5 random numbers from the randomly filled list I tried to use this code:
import random
a = random.sample(range(1,1000),10)
for a in range(5):
print(a)
but this gives me only that:
0
1
2
3
4
I know it has to be something about the range(5) but I assume that the loop doesn't choose the numbers from the list I created, am I right?
Can someone help me here?
CodePudding user response:
random.sample
returns unique random elements - i.e. if you sample 10 elements from a list of 10 elements - all elements are guaranteed to be there
From the docs help(random.sample)
-
sample(population, k) method of random.Random instance Chooses k unique random elements from a population sequence or set.
To sample with repetition, you can use the choices
function -
From the docs - help(random.choices)
choices(population, weights=None, *, cum_weights=None, k=1) method of random.Random instance Return a k sized list of population elements chosen with replacement.
For example,
b = random.choices(range(1, 11), k=10)
print(b)
# [1, 10, 9, 8, 6, 1, 6, 4, 9, 3]