Home > front end >  Generating a random with a specific limited size
Generating a random with a specific limited size

Time:10-06

Could someone explain to me how I can use random to generate a list consisting of numbers that differ from 0 to 9 and the size should be fixed between 49 and 98?

random_number = [random.randint(0,9) for _ in range()]

I think I should use this line, but I am not sure how to limit the random_number which gets generated to be a number consisting of 49 to 98 numbers.

Could someone help me clarifying this?

CodePudding user response:

You can use random.choices to generate a list of random entries from a range, pass k= to determine the size. We can pass k=random.randint(49, 98) to generate a list with a random length in that range

import random
random.choices(range(0, 9), k=random.randint(49, 98))

CodePudding user response:

[random.randint(0,9) for _ in range(random.randint(49,98))]

This should do what you want, no? Range accepts a number, so if we randomly generate a number between 49 and 98 and pass it to range, we'll get a list of 49 to 98 items, which will be iterated over.

Edit: Seems a comment beat me to it. Tragic.

  • Related