mardi 7 juin 2022

Fill a list with 10 random numbers, then chose 5 of them randomly

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 wich Is way to long :D

If I want to choose 5 randoms 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?




Aucun commentaire:

Enregistrer un commentaire